noazark
noazark

Reputation: 289

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_json(: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

Upvotes: 2

Views: 3662

Answers (2)

BurmajaM
BurmajaM

Reputation: 724

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

Upvotes: 14

Mike Lewis
Mike Lewis

Reputation: 64147

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.

Upvotes: 2

Related Questions