Oleg Gutsol
Oleg Gutsol

Reputation: 13

How to sanitize an object obtained with belongs_to in rails 3

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.

Upvotes: 1

Views: 435

Answers (1)

Toby Hede
Toby Hede

Reputation: 37123

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 ])

Upvotes: 1

Related Questions