比较来自世界各地的卖家的域名和 IT 服务价格

建立一个句子 Rails ActiveRecord where

如何最好地建立 where 使用 Rails ActiveRecord? 例如,假设我有一个返回博客列表的控制器的动作:


def index
@posts = Post.all
end


现在假设我希望能够传输参数 url 因此,控制器的此操作仅返回某个作者的消息:


def index
author_id = params[:author_id]

if author_id.nil?
@posts = Post.all
else
@posts = Post.where/"author = ?", author_id/
end
end


我不喜欢它。 如果我向页面添加了一个订购或分区,或者更差,更差的查询字符串的可选参数 URL 要过滤,此操作控制器将变得非常复杂。
已邀请:

奔跑吧少年

赞同来自:

关于什么:


def index
author_id = params[:author_id]

@posts = Post.scoped

@post = @post.where/:author_id => author_id/ if author_id.present?

@post = @post.where/:some_other_condition => some_other_value/ if some_other_value.present?
end



Post.scoped

- 它基本上是懒惰的加载量 Post.all /只要 Post.all 立即返回一个数组
, 尽管 Post.scoped 刚返回关系的对象/. 此请求将无法完成,直到
你真的不会试图在演示中重复它 /打电话 .each/.

卫东

赞同来自:

MMMM,您要使用的最佳方法可能是它的传播 2 行动


def index
@post = Post.all
end

def get
@post = Post.where/"author=?", params[:author_id]/
end


IMHO 如果你想到的话,它有更多的意义 RESTful API, 索引意味着挽救一切并获得 /或表演/, 得到要求并显示它!

风见雨下

赞同来自:

这个问题很老,但它仍然很高 google 在 2019 一年,以及一些早期的答案已经过时,所以我决定分享一个可能的解决方案。

有些区域被引入模型中,存在参数的存在:


class Post
scope :where_author_ids, ->/ids/{ where/author_id: ids.split/‘,’// if ids }
scope :where_topic_ids, ->/ids/{ where/topic_id: ids.split/‘,’// if ids }


然后在控制器中,您可以简单地放置如此多的过滤器,例如:


def list
@posts = Post.where_author_ids/params[:author_ids]/
.where_topic_ids/params[:topic_ids]/
.where_other_condition_ids/params[:other_condition_ids]/
.order/:created_at/


然后参数可以是以逗号分隔的一个值或值列表,另一个值正常。

如果一个 param 不存在,他只是错过了这句话 where 它不会通过此特定标准过滤。 如果存在参数,它是一个空字符串,它将 "过滤" 全部。

当然,这一决定不会达到所有情况。 如果您有一个具有多个过滤器的视点页面,但在第一次打开时,要显示所有数据,并且在按下按钮之前没有数据 "发送" 或类似的东西 /这个控制器会如何做到/, 你将不得不修复它。

我试过了 SQL 注射了它 rails, 似乎它会很好地应对,以便尽我所能保持安全。

裸奔

赞同来自:

这是这样的工作吗?


def get
raise "Bad parameters...why are you doing this?" unless params[:filter].is_a?/Hash/
@post = Post.where/params[:filter]/
end


然后你可以做一些这样的事情:
? filter[author_id]=1&filter[post_date]= ... 等等。

君笑尘

赞同来自:

你必须模拟 url, 使用投资资源。 预期的 url 将 /authors/1/posts. 想想作者作为资源。 阅读本手册中投资资源:
http://guides.rubyonrails.org/routing.html
/滚动到2.7投资的资源/.

要回复问题请先登录注册