Retrieve all entries except those that have an empty column in Rails

How to get all link entries except url columns that are empty? My controller looks like this:

  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 => @links }

    end
  end

Thanks in advance!

Edit # 1

If I do this:

@links = @user.all(:conditions => 'url != NULL')

I get an error message:

NoMethodError in UsersController#show 
undefined method `all' for #<User:0x2254f98>

And if I do this:

@links = @user.links.all(:conditions => 'url != NULL')

I still get all the links, even those that have empty url fields ...

Edit # 2

If i do

@links = User.all(:conditions => 'url != NULL')

I get

ActiveRecord::StatementInvalid in UsersController#show
SQLite3::SQLException: no such column: url: SELECT * FROM "users" WHERE (url != NULL) 

And if I do

@links = Link.all(:conditions => 'url != NULL')

I still get all the links, even those that have empty url fields ...

I am wondering if the difference between NULL and field is not different?

Edit # 3

Now my code is as follows:

  def show
    @user = User.find_by_username(params[:username])
    @links = @user.links.all(:conditions => "url <> ''")

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @links }

    end
  end

Decision

#controller
@links = @user.links.not_null_url

#model
named_scope :not_null_url, :conditions => "url <> ''"

It works! Just make sure to access the links:

#view
<% @links.each do |link| %>

And not:

#view
<% @user.links.each do |link| %>
+3
source share
5 answers

its not @userhim

User.all(:conditions => 'url != NULL')

EDIT:

. "links" ?

№ 2

: @user.links.all(:conditions => {:url => !nil})

№ 3

! url IS NOT NULL URL != NULL - NULL , , , . :

@user.links.all(:conditions => "url <> ''")

@klew, , named_scope:

#model
named_scope :not_null_url, :conditions => "url <> ''"

#controller
@user.links.not_null_url
+6

Try:

@links = @user.links.all(:conditions => "url IS NOT NULL")

, named_scope Link:

named_scope :not_null_url, :conditions => "url IS NOT NULL"

:

@links = @user.links.not_null_url
+1

: ORM WHERE SQL, SQL.

Somewhere in Rails there is an easy way to pass it ("select * from users, where username, for example" @username "and url not null, username) as a parameterized request, and pass it a set of records.

This is trivial in the real world, but your structure makes it difficult. Step outside to the second ...

0
source

@user.all(:conditions => 'url != NULL')

0
source

You can also do this in the Rails3 Table.where (: col1 =>! Nil ,: col1 =>! Nil)

0
source

Source: https://habr.com/ru/post/1736540/


All Articles