Rails Search Form

后端 未结 4 593
北海茫月
北海茫月 2021-02-01 00:05

I\'m creating an application that tracks users and achievements (think, xbox live, etc.) These tables are linked via a join table. I would like to have a search form on my inde

4条回答
  •  天涯浪人
    2021-02-01 00:21

    Here's a bit of skeleton code to get you started based off what I think you need from what you have said. I hope this is useful.

    For the search bit you could do something like this in your index view:

    <%= form_for User.new, :url => "search" do |f| %>
      <%= f.label :name %>
      <%- f.text_field :name %>
    <%- end %>
    

    In your controller:

    def search
      q = params[:user][:name]
      @users = User.find(:all, :conditions => ["name LIKE %?%",q])
    end
    

    and in your search view:

    <%-@users.each do |user| %>
      Name: <%=user.name %>
    
      <%- user.achievements.each do |achievement| %>
        <%= achievement.name %>
      <%- end %>
    <%- end %>
    

    You would, of course, need to ensure the users and achievement models are correctly linked:

    class User << ActiveRecord::Base
      has_many :achievements
    
    end
    

提交回复
热议问题