如何使用可选属性来选择文章?
#routes.rb
get "/:year(/:month(/:day))(/:genre)" => "archives#index", :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }
#archives_controller.rb
def index
@articles = Article.all(params[:year, :month, :day, :genre],:order => "created_at DESC")
我希望能够按年、或按年和月、或按年和月和日获取文章,并且可以选择在其中任何一个的末尾添加类型。我可以在一条语句中执行此操作还是需要 if 块?另外,我希望能够获得特定类型的所有文章,但我认为我需要在单独的操作中做到这一点?谢谢!
更新
我最终使用了metawhere gem 加上一种方法来构建我的日期:
def index
date_builder
@articles = Article.where(:created_at.matches % @date, :genre.matches % @genre).order("created_at DESC")
respond_to do |format|
format.json { render :json => @articles }
format.xml { render :xml => @articles }
format.html
end
end
def date_builder
@date = ""
@date += params[:year] if !(params[:year].nil?)
@date += "-" + params[:month] if !(params[:month].nil?)
@date += "-" + params[:day] if !(params[:day].nil?)
@date += "%"
end
这将sql 调用的数量减少到一个并使一切看起来都很漂亮。感谢您的帮助!
#routes.rb
get "/:year(/:month(/:day))(/:genre)" => "archives#index", :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }
#archives_controller.rb
def index
@articles = Article.all(params[:year, :month, :day, :genre],:order => "created_at DESC")
I want to be able to get the articles by year, or year and month, or year and month and day, with genre optionally on the end of any of those. Can I do this in one statement or do I need if blocks? Also I want to be able to get all the articles in a specific genre, but I think I need to do that in a separate action? Thanks!
UPDATE
I ended up using the metawhere gem plus a method to build my date:
def index
date_builder
@articles = Article.where(:created_at.matches % @date, :genre.matches % @genre).order("created_at DESC")
respond_to do |format|
format.json { render :json => @articles }
format.xml { render :xml => @articles }
format.html
end
end
def date_builder
@date = ""
@date += params[:year] if !(params[:year].nil?)
@date += "-" + params[:month] if !(params[:month].nil?)
@date += "-" + params[:day] if !(params[:day].nil?)
@date += "%"
end
This reduced the number of sql calls to one and make everything look pretty. Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果请求中存在匹配的参数,您可以使用
has_scope
gem 定义一些要应用于您的集合的范围。您可以在此处找到 has_scope。其他替代方案可能是
meta-where
和meta-search
gem。您可以在此处找到有关如何使用它们的说明。You can use
has_scope
gem to define some scopes to be applied to your collection if there're matching params in the request. You can find has_scope here.Other alternative could be the
meta-where
andmeta-search
gems. You can find an explanation on how to use them here.你可以这样做:
You could do something like this: