My app has user, photo, and state models with the following setup:
A state has many users.
A user has many photos.
I have the photos view set up as the homepage (application.root). I am trying to set up a select tag to filter the photos w.r.t the selected state.
In View:
<%= form_tag photos_path, :method => 'get' do%>
<%= select("state", "name", State.all.collect(&:name)) %>
<%= submit_tag "State" %>
<% end %>
In Controller:
if params[:state]
statesmen = State.find_by_name(params[:state][:name]).users
statesmen.each do |person|
@photos = @photos << Photo.where(:user_id => person.id)
end
end
Questions:
- Is there a better way to collect the photos?
- Currently, the photos table only has a
user_idcolumn. Should I just create astate_idcolumn too? - What’s wrong with the current approach?
So your associations are set up as follows:
state.rb
user.rb
photo.rb
Just add to state.rb
Then you can do just: