开发者

Hiding Rails Model Attributes

I have a controller for an API that looks like this:

def index
  respond_to   do |format|
    format.json  { render :json => @groups.to_json(:only => [:id, :name, :description, :created_at, :updated_at])}
  end
end

def show
  respond_to   do |format|
    format.json  { render :json => @group.to_json(:only => [:id, :name, :description, :created_at, :updated_at]) }
  end
end

# @todo add store to item
def create
  if @group.save
    render :json => @group.to_json(:only => [:id, :name, :description, :created_at, :updated_at])
  else
    render :status => 406
  end
end

def update
  if @group.update_attributes(params[:group])
    render :json => @group.to_js开发者_开发问答on(:only => [:id, :name, :description, :created_at, :updated_at])
  else
    render :status => 406
  end
end

def destroy
  @group.destroy
  render :text => ""
end

As you can see, I'm repeating my self a lot. I'd love to make these (and only these) attributes available by way of the model, but couldn't find a fitting solution. Is there anything to protect attributes from mass writing? Or do I possibly mean mass reading?

As noted in comments below I want to have a model with attributes, name and i_am_private. When I render that model as json - render :json => @model - I want only name to show up.

Ruby 1.8.7 Rails 3


How about overriding as_json method in your Group model?

class Group < ActiveRecord:Base
  ...
  def as_json(options={})
    {
      :id => id,
      :name => name,
      :description => description,
      :created_at => created_at,
      :updated_at => updated_at
    }
  end
end


To prevent mass assignment, add the following to your model:

  attr_accessible :attr1, :attr2, :attr3

where attr1, attr2, attr3 and so on are the attributes you want to allow for mass assignment, the rest of the attributes for that model will not be allowed for mass assignment.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜