如何清理在rails 3中使用belongs_to获得的对象
我有两个类:用户和消息。下面是定义:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您手动渲染视图中的对象,则无需清理 - 响应将仅包含您公开的元素。
如果您使用 AJAX 和 to_json,有多种方法可以删除信息。您可以在初始 Model.find 中使用选择来确保敏感信息实际上不会从查询中返回。有关详细信息,请参阅Active Record 查询 - 选择特定字段。
另一种方法是覆盖 JSON 渲染本身以仅显示必需的字段,使用:
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: