如何清理在rails 3中使用belongs_to获得的对象

发布于 2024-10-08 03:15:19 字数 657 浏览 8 评论 0原文

我有两个类:用户和消息。下面是定义:

class Message < ActiveRecord::Base
  belongs_to  :receiver, :class_name => 'User', :foreign_key  => 'receiver'
  belongs_to  :sender, :class_name   => 'User', :foreign_key  => 'sender'
end

class User < ActiveRecord::Base
  has_many :incoming_messages, :class_name => 'Message', :foreign_key => 'receiver'
  has_many :outgoing_messages, :class_name => 'Message', :foreign_key => 'sender'
end

当我在控制器中收到消息时,我还会获取 User 对象

@message.receiver 

@message.sender

这些对象包含一些用户信息(密码等),我想在将其传递到视图之前将其删除(在我的例子中是一个 json 对象) )。这样做的最佳方法是什么?

感谢您的帮助。

I have two classes: User and Message. Below are the definitions:

class Message < ActiveRecord::Base
  belongs_to  :receiver, :class_name => 'User', :foreign_key  => 'receiver'
  belongs_to  :sender, :class_name   => 'User', :foreign_key  => 'sender'
end

class User < ActiveRecord::Base
  has_many :incoming_messages, :class_name => 'Message', :foreign_key => 'receiver'
  has_many :outgoing_messages, :class_name => 'Message', :foreign_key => 'sender'
end

When I get messages in the controller, I also get the User objects in

@message.receiver 

and

@message.sender

These objects contain some user information (passwords etc) that I would like to remove before passing it to the view (a json object in my case). What is the best way of doing this?

Thanks for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风来 2024-10-15 03:15:19

如果您手动渲染视图中的对象,则无需清理 - 响应将仅包含您公开的元素。

如果您使用 AJAX 和 to_json,有多种方法可以删除信息。您可以在初始 Model.find 中使用选择来确保敏感信息实际上不会从查询中返回。有关详细信息,请参阅Active Record 查询 - 选择特定字段

另一种方法是覆盖 JSON 渲染本身以仅显示必需的字段,使用:

to_json(:only => [ :column, :column ])

If you are manually rendering the objects in the view, no need to sanitize - the response will only contain the elements you expose.

If you are using AJAX and to_json, there are several ways of removing the information. You can use a select in the initial Model.find to ensure that the senstive information is not actually returned from the query. See Active Record Querying - selecting specific fields for more.

The alternative is to override the JSON rendering itself to only display the required fields, using:

to_json(:only => [ :column, :column ])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文