0

This might be extremely simple: I have a controller that returns a user object when passed a param.

def show
  if params[:mob]
    user = User.find(params[:id])
    respond_with([user.establishments,
                user])

this returns the entire user object. That is a problem because on the user object is the encrypted password, hash, and various other pieces of data I do not want to expose.

What would be the proper syntax to have it return the user object less some specified attributes? I am looking for a solution where I do not have manually create a new hash out of the user attributes I want to expose because it would be must simpler to just say, "give me user without x and y" than "give me a hash of user.a, user.b, user.c, ... user.n"

thx!

istan
  • 1,349
  • 3
  • 21
  • 36

3 Answers3

2

I'm assuming this is a problem for when you return the data in xml or json.

You can get around this by doing something like this to exclude certain fields.

obj.to_xml(:except => [ :created_at, :updated_at ])

or you can override the to_xml function in the model to always exclude values.

Scott
  • 1,105
  • 1
  • 7
  • 17
  • yes exactly the case. this is the method I am looking for. but how to apply it without calling .to_json first? My controller is already responding with format json so calling to_json is redundant. Can I call the :except block directly on the user? How? thx! – istan May 13 '11 at 20:01
  • you could override it in your model to always do that, see this post http://stackoverflow.com/questions/2572284/override-to-json-in-rails-2-3-5 – Scott May 14 '11 at 19:01
1

Here's a another suggestion.

Create a new method that "sanitizes" the user:

class User < ActiveRecord::Base
  ...
  def strip_sensitive_data!
    [:password, :ssn, :birth_date].each { |m| send("#{m}=", nil) }
  end
  ...
end

user = User.find(params[:id]).strip_sensitive_data!
twmills
  • 2,985
  • 22
  • 20
0

Can you add a instance method on the User object which would return a new User object with the required attributes?

Aj Gu
  • 1,509
  • 9
  • 12