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
How about overriding as_json method in your Group model?