[英]Ruby on Rails chaning methods on ActiveRecord doesnt work?
I got this code, and i get the "Missing method" when i try to use the second more elegant approach. 我得到了这段代码,当我尝试使用第二种更优雅的方法时,我得到了“缺少方法”。 I think the documentation at: http://guides.rubyonrails.org/active_record_querying.html is rather unhelpful or incomplete.
我认为位于http://guides.rubyonrails.org/active_record_querying.html的文档是没有帮助或不完整的。 Any ideas?
有任何想法吗?
By the way, feel free to help write an even more "oneliner" elegant approach to this :) 顺便说一句,随时帮助编写一个更加“单一”的优雅方法:)
def index
@sortby = params[:sort_by]
# THIS WORKS
#if @sortby == nil
# @movies = Movie.all
#else
# @movies = Movie.order(@sortby)
#end
# THIS DOESNT. WHY? I THOUGHT METHOD CHAINING AND LAZYLOAD WOULD WORK.
@movies = Movie.all
@movies = @movies.order(@sortby) unless @sortby == nil
end 结束
You can do this in one line. 您可以一行完成此操作。
@movies = params[:sort_by].nil? ? Movie.all : Movie.order(params[:sort_by]).all
In your case you are getting error about 'undefined method order for Array' I suppose. 我想在您的情况下,您会遇到有关“数组的未定义方法顺序”的错误。 ActiveRecord method .all returns array.
ActiveRecord方法.all返回数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.