I am trying to get data for my collection_select list.
Details
There are 4 tables involved
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
If I would have to write in plain SQL, it would be like below.This sql is for postgreSQL. I would like to write in rails 3.2.1 syntax.
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
As a result, I want to get signed_posts.id and posts.title – organizations.name for a volunteer id 1
which I would like to use on dropdown list.
Thank you very much for your help
My Solution
I solved the problem using hash table like this one
@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
On View
<%=select_tag 'ddl_test',options_for_select(@ddl_test.to_a),:prompt => 'Please select the project'%>
There are a couple ways to do this. In your controller you would want a statement such as:
After that, one way would be to create a method in your
SignedPostmodel to return the data you need, something like the followingThen, in your collection_select, you can use (this is partially guessing, since I don’t know the specifics of your form):
Edit based on question updates
If you want to use
select_tagandoptions_for_selectas you did in your solution, a more elegant way would be to create this variable in your controller:Then in your view: