我有三个表,其中一个是另外两个表之间的连接表。
- 职位:id
- 县:id
- 县化:job_ib、county_id
我想创建一个特定工作关联的县列表。我正在尝试使用类似的东西:
<%= @counties.map { |county| county.id }.join(", ") %>
但这显然没有使用 countyizations 表。我怎样才能改变上面的代码来完成我需要的?另外,我想按 ASC
顺序按字母顺序列出县。
附言
我想我应该添加我如何在我的模型中链接我的表。
- 工作:has_many :countyizations & has_many :counties, :through => :countyizations
- 县:has_many :countyizations & has_many :jobs, :through => :countyizations
- 县化:belongs_to :county & belongs_to :job
最佳答案
对于给定的 job.id
,您可以使用它返回所有由给定工作过滤的 counties
。
<%= @counties.order('name asc').includes(:jobs).where('jobs.id = ?', job.id) %>
根据您的要求替换 job.id
,您可以在 Controller 中设置一个 @job
实例变量并在 View 中使用。
或者甚至更好地将此代码移动到 Controller 操作:
# controller
def show
job_name = ...
@counties = ...
@county_jobs = @counties.order('name asc').includes(:jobs).where(jobs.name = ?', job_name)
end
然后在你的 View 中,显示所有拥有搜索工作的县:
<%= @counties.map(&:id).join.(',') %>
关于ruby-on-rails - Rails - 通过连接表以逗号分隔的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21422219/