문제

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.

도움이 되었습니까?

해결책

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 ])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top