我正在尝试为我的 collection_select 列表获取数据。
细节
涉及4张表
volunteers
has_many :signed_posts
has_many :posts, :through=>:signed_posts
signed_posts
belongs_to :volunteer
belongs_to :post
posts
belongs_to :organization
has_many :signed_posts
has_many :volunteers, :through=>:signed_posts
organizations
has_many :post
如果我必须用纯 SQL 编写,它会像下面这样。这个 sql 是用于 postgreSQL 的。我想用 rails 3.2.1 语法写。
Select sp.id,p.title ||'-'|| o.name AS project from signed_posts sp
inner join volunteers v on v.id=sp.volunteer_id
inner join posts p on p.id=sp.post_id
inner join organizations o on o.id=p.organization_id
where v.id=1
结果,我想为志愿者 id 1获取signed_posts.id和posts.title - organizations.name
我想在下拉列表中使用它。
非常感谢您的帮助
我的解决方案
我使用像这样的哈希表解决了这个问题
@signed_projects=Volunteer.find(1).signed_posts.joins(:post)
@ddl_test=Hash.new
@signed_projects.each do |signed_project|
ddl_test[signed_project.post.title+"-"+signed_project.post.organization.name]=signed_project.id
end
在视图中
<%=select_tag 'ddl_test',options_for_select(@ddl_test.to_a),:prompt => 'Please select the project'%>