Alf*_*red 3 sqlite activerecord ruby-on-rails
如何获取所有"链接"条目,并删除那些空白的"网址"列?我的控制器看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
提前致谢!
编辑#1
如果我做:
@links = @user.all(:conditions => 'url != NULL')
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
NoMethodError in UsersController#show
undefined method `all' for #<User:0x2254f98>
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
@links = @user.links.all(:conditions => 'url != NULL')
Run Code Online (Sandbox Code Playgroud)
我仍然获得所有链接,即使是那些有空网址的链接......
编辑#2
如果我做
@links = User.all(:conditions => 'url != NULL')
Run Code Online (Sandbox Code Playgroud)
我明白了
ActiveRecord::StatementInvalid in UsersController#show
SQLite3::SQLException: no such column: url: SELECT * FROM "users" WHERE (url != NULL)
Run Code Online (Sandbox Code Playgroud)
如果我这样做
@links = Link.all(:conditions => 'url != NULL')
Run Code Online (Sandbox Code Playgroud)
我仍然获得所有链接,即使是那些有空网址的链接......
我想知道这是否与空白字段之间有区别?
编辑#3
现在我的代码看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
解
#controller
@links = @user.links.not_null_url
#model
named_scope :not_null_url, :conditions => "url <> ''"
Run Code Online (Sandbox Code Playgroud)
这有效!请务必访问以下链接:
#view
<% @links.each do |link| %>
Run Code Online (Sandbox Code Playgroud)
并不是:
#view
<% @user.links.each do |link| %>
Run Code Online (Sandbox Code Playgroud)
它不是@user,它的
User.all(:conditions => 'url != NULL')
Run Code Online (Sandbox Code Playgroud)
编辑:
其实我有一个疑问.是"links"一列插件的用户表或者是一个模式?
编辑#2
你这个: @user.links.all(:conditions => {:url => !nil})
编辑#3
找到了!url IS NOT NULL或者URL != NULL任何使用NULL都无法解决您的问题,因为正如您所说,null和空字段之间存在差异.以下代码对我有用:
@user.links.all(:conditions => "url <> ''")
Run Code Online (Sandbox Code Playgroud)
正如@klew建议的那样,如果使用的话会更好named_scope:
#model
named_scope :not_null_url, :conditions => "url <> ''"
#controller
@user.links.not_null_url
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5548 次 |
| 最近记录: |