简体   繁体   中英

How can I make RABL render an attribute only if it exists in the object?

I have a RESTful User model and am trying to filter attributes to be included in the Show JSON response when the User object being sought is not the current user.

Logic:

if params[:id]==current_user
  json => {:name: <name value>, :birthdate: <birthdate>}
else
  json => {:name: <name value>}
end

When I filter attributes in the controller, I get a MissingAttribuiteError with the following code:

UsersController

def show
  if params[:id]==current_user.id.to_s
    @user=User.find(params[:id])
  else
    @user=User.find(params[:id], :select => [:name])
  end
  respond_with(@user)
end

users/show.json.rabl

object @user
attributes :name, :birthdate

How can I make RABL render an attribute only if it exists in the object?

Apparently easy things should be easy. This works.

[Not sure if filtering on the view level is better or worse than filtering in the controller, though.]

UsersController

def show
    @user=User.find(params[:id])
    respond_with(@user)
end

users/show.json.rabl

if @user==current_user
  attributes :birthdate
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM