我正在尝试为我的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
因此,我希望获得志愿者身份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'%>
答案 0 :(得分:0)
有几种方法可以做到这一点。在您的控制器中,您需要一个声明,如:
@signed_posts = Volunteer.find(1).signed_posts.includes({:post => :organization})
之后,一种方法是在SignedPost
模型中创建一个方法来返回所需的数据,如下所示
def post_name_with_organization
"#{id} #{post.title} - #{post.organization.name}"
end
然后,在你的collection_select中,你可以使用(这是部分猜测,因为我不知道你的表单的细节):
form.collection_select(:signed_post_id, @signed_posts, :id, :post_name_with_organization)
根据问题更新进行修改
如果您想在解决方案中使用select_tag
和options_for_select
,则更优雅的方法是在控制器中创建此变量:
@signed_posts_options = @signed_posts.map {|sp| [sp.post_name_with_organization, sp.id]}
然后在你看来:
<%=select_tag 'ddl_test',options_for_select(@signed_posts_options),:prompt => 'Please select the project'%>