隐藏 Rails 模型属性 [英] Hiding Rails Model Attributes
问题描述
我有一个 API 控制器,如下所示:
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?
如下面的评论所述,我想要一个带有属性的模型,name
和 i_am_private
.当我将该模型渲染为 json - render :json =>@model
- 我只想显示 name
.
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.
红宝石 1.8.7导轨 3
Ruby 1.8.7 Rails 3
推荐答案
如何在你的 Group 模型中重写 as_json 方法?
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
这篇关于隐藏 Rails 模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!