Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several ways to do that:</p> <pre><code># with old hash syntax (all ruby versions) @clients = Client.where(:name =&gt; params[:find_it]) # with new hash syntax (ruby 1.9) @clients = Client.where(name: params[:find_it]) # with text query @clients = Client.where('name = ?', params[:find_it]) </code></pre> <p>All of them are equivalent.</p> <p>Code <code>@post = Client.all</code> assigns variable <code>@post</code> with <strong>all</strong> clients from database and then you reassign it two times with completely different values. In the end your variable <code>@post</code> is assigned with <code>Client</code> record with id equals to <code>params[:id]</code> and this is what will you get in a view.</p> <p>Also in general you don't have to use <code>all</code> method. Notice that:</p> <pre><code>Client.where(name: params[:find_it]).all.class # =&gt; Array Client.where(name: params[:find_it]).class # =&gt; ActiveRecord::Relation </code></pre> <p>It means that you can query <code>ActiveRecord::Relation</code> with other querying methods i.e.</p> <pre><code>@clients = Client.where(name: params[:find_it]) @favourite_clients = @clients.where(favourite: true) </code></pre> <p>Rails will know what to do (it won't process <code>ActiveRecord::Relation</code> until it has to do something with it, i.e. while iterating result in a view), so you would want to add <code>all</code> only when you really need array in controller. </p> <p>You should also consider using more meaningful variables names like <code>@clients</code> instead of <code>@post</code>.</p> <p>When it comes to whole solution it should be more like:</p> <pre><code># view &lt;%= form_for :find_it, :url =&gt; find_client_path do |n| %&gt; Name: &lt;%= n.text_field :text, :cols =&gt; "30", :rows =&gt; "1" %&gt;&lt;/br&gt; &lt;%= n.submit "Find" %&gt; &lt;% end %&gt; </code></pre> <p>Take a look at <code>form_for</code> <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for" rel="nofollow">documentation</a>. You can find out that your text is not <code>params[:find_it]</code>, but <code>params[:find_it][:text]</code>.</p> <p>You have to provide <code>:url</code> option with path to your <code>find_it</code> action.</p> <p>If you want to show results on index view, you can do it like:</p> <pre><code># view &lt;%= form_for :find_it do |n| %&gt; Name: &lt;%= n.text_field :text, :cols =&gt; "30", :rows =&gt; "1" %&gt;&lt;/br&gt; &lt;%= n.submit "Find" %&gt; &lt;% end %&gt; # controller def index @clients = Client.scoped @clients = @clients.where(:name =&gt; params[:find_it][:text]) if params[:find_it] end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload