开发者

retrieve user object less specified attributes

This might be extremely simple: I have a controller that returns a user object when passed a para开发者_如何学JAVAm.

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!


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.


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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜