ruby - How to filter with multiple parameters in Rails? -
i'm building app in users submit posts, tag them year, location, , military unit in. on index page, i'd have 3 dropdowns year location , military unit, , when user specifies different values in dropdowns, index filters through posts parameters. however, i've failed on , over.
here's posts controller:
def index @posts = post.all @posts = @posts.location(params[:location]) if params[:location].present? @posts = @posts.unit(params[:unit]) if params[:unit].present? @posts = @posts.year(params[:year]) if params[:year].present? end my index view:
<h1>all posts</h1> <%= form_tag 'search', method: 'get' %> <%= select :location, options_for_select(countries) %> <%= select :year, time.now.year.downto(1900).to_a %> <%= select :unit, options_for_select(["army", "navy"]) %> <%= submit_tag "filter" %> <% end %> </p> <ul id="posts"> <% @posts.each |post| %> <li> <%= link_to post.id, post_path(post) %> </li> <% end %> <%= link_to "new post", new_post_path %> </ul> and posts model:
class post < activerecord::base belongs_to :user has_many :comments has_attached_file :image validates_attachment_content_type :image, :content_type => ["image/jpg","image/jpeg","image/png"] end with right now, error i'm receiving "nomethoderror in posts#index" : "undefined method `empty?' nil:nilclass". highlighted line view:
<%= select :location_id, options_for_select(countries) %> thanks this. i've searched , not found has helped.
edit: countries comes following helper:
module countrieshelper def countries [ "afghanistan", "aland islands", "albania", "algeria", #truncated space "western sahara", "yemen", "zambia", "zimbabwe" ] end end
the select array needs formatted this:
def countries [ ["afghanistan","afghanistan"], ["aland islands","aland islands"], ["albania","albania"], , on . . . ] then use select options in search per example snippet:
<%= select_tag :search, options_for_select(countries), prompt: "choose country", class: 'your_css_class_here' %> there might other issues, set helper array properly. let me know happens , can add answer.
Comments
Post a Comment