2

Here are some request to a search page I have

/articles?tag=tag1&author=author1
/articles?title=title1&tag=tag1
/articles?title=title1&tag=tag1&author=author1
/articles?tag=tag1
/articles?title=title1&tag=tag1&author=author1&size=medium&is_deprecated=false&has_fotos=true

Well, what is the most efficient way to make a request to Article model depending on a query? I wouldn't like to do something like this

@articles = Article.all
@articles = Article.find_by_tag(params[:tag]) if params[:tag]
@articles = Article.where("title like ?", params[:title]) if params[:title]
@articles = Article.find_by_author(params[:author]) if params[:author]
@articles = Article.find_by_is_deprecated(params[:is_deprecated]) if params[:is_deprecated]
#...etc

Your thoughts?

4

1 回答 1

1

无需每次都执行 sql 查询...使用 ruby​​ 方式。您可以使用以下方法..

@articles = Article.all

@articles.select!{ |article| article.tag==params[:tag] } if params[:tag].present?

@articles.select!{ |article| article.title==params[:title]} if params[:title].present?

@articles.select!{ |article| article.author==params[:author]} if params[:author].present?

@articles.select!{ |article| article.is_deprecated==params[:is_deprecated]} if params[:is_deprecated].present?
于 2013-04-11T05:13:11.150 回答