Note that there are some explanatory texts on larger screens.

plurals
  1. POFetch all entries exept those with empty column in Rails
    text
    copied!<p>How do I fetch all 'link' entries exept those with an 'url' column that is blank? My controller looks like this:</p> <pre><code> def show @user = User.find_by_username(params[:username]) @links = @user.links.all respond_to do |format| format.html # show.html.erb format.xml { render :xml =&gt; @links } end end </code></pre> <p>Thanks in advance!</p> <p><strong>Edit #1</strong></p> <p>If I do:</p> <pre><code>@links = @user.all(:conditions =&gt; 'url != NULL') </code></pre> <p>I get a error:</p> <pre><code>NoMethodError in UsersController#show undefined method `all' for #&lt;User:0x2254f98&gt; </code></pre> <p>And if I do:</p> <pre><code>@links = @user.links.all(:conditions =&gt; 'url != NULL') </code></pre> <p>I still get all the links, even those with empty url fields...</p> <p><strong>Edit #2</strong></p> <p>If I do</p> <pre><code>@links = User.all(:conditions =&gt; 'url != NULL') </code></pre> <p>I get </p> <pre><code>ActiveRecord::StatementInvalid in UsersController#show SQLite3::SQLException: no such column: url: SELECT * FROM "users" WHERE (url != NULL) </code></pre> <p>And if I do</p> <pre><code>@links = Link.all(:conditions =&gt; 'url != NULL') </code></pre> <p>I still get all the links, even those with empty url fields...</p> <p>I'm wondering if it's a difference between NULL and the field beeing empty?</p> <p><strong>Edit #3</strong></p> <p>Now my code looks like this:</p> <pre><code> def show @user = User.find_by_username(params[:username]) @links = @user.links.all(:conditions =&gt; "url &lt;&gt; ''") respond_to do |format| format.html # show.html.erb format.xml { render :xml =&gt; @links } end end </code></pre> <p><strong>Solution</strong></p> <pre><code>#controller @links = @user.links.not_null_url #model named_scope :not_null_url, :conditions =&gt; "url &lt;&gt; ''" </code></pre> <p>This works! Just be sure access the links with:</p> <pre><code>#view &lt;% @links.each do |link| %&gt; </code></pre> <p>And not:</p> <pre><code>#view &lt;% @user.links.each do |link| %&gt; </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