我有一个名为Agents的rails模型。我的任务是按州和行业过滤代理商。端点应该是GET请求:
/api/agents?state=OH&industry=Professional%20Beer%20Taste-Tester
我已经尝试使用范围,但我似乎无法打电话给所有按州和行业过滤的代理。这是我的模型:
agent.rb
class Agent < ApplicationRecord
has_many :licenses
has_and_belongs_to_many :carriers
validates :name, presence: true
validates :phone_number, presence: true
end
attributes: name, phone_number
license.rb
class License < ApplicationRecord
belongs_to :agent
validates :state, presence: true
end
attributes: state
industry.rb
class Industry < ApplicationRecord
has_and_belongs_to_many :carriers
validates :name, presence: true
end
attributes: name
carrier.rb
class Carrier < ApplicationRecord
has_and_belongs_to_many :industries
validates :name, presence: true
end
attributes: name
这是我到目前为止所尝试的:
Agent.includes(:licenses).where(licenses: { state: 'OH' })
这给了我一个代理商列表,其许可证位于“OH”但我无法弄清楚如何添加AND以获得其许可证位于“OH”且其行业名称为“Professional Beer Taste-Tester”的代理商”。
发布于 2019-04-24 14:14:42
你的控制器在哪里......?使用HABTM,你应该使用外键来获得好的结果,就像你的模型一样
has_and_belongs_to_many :carriers, foreign_key: :industry_id
还要确保您的数据库中有列。
你的action很重要。我能看一下吗?
https://stackoverflow.com/questions/-100006664
复制相似问题