2011-03-18 54 views
2

我有一個控制器,看起來像這樣的API:隱藏Rails的模型屬性

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 

正如你所看到的,我重複我自己很多。我希望通過模型提供這些(並且只有這些)屬性,但找不到合適的解決方案。有什麼可以保護大衆文字的屬性嗎?或者我可能是指大衆閱讀?

正如在下面的評論中指出的,我想要一個具有屬性的模型,namei_am_private。當我將該模型渲染爲json - render :json => @model - 我只想要顯示name

的Ruby 1.8.7 的Rails 3

+0

似乎是 重複(http://stackoverflow.com/questions/4550925/filter-a-models-attributes-before-outputting-as- [過濾一個模型的屬性輸出爲JSON之前] json) – Zabba 2011-03-18 08:14:14

+0

你也會發現這個有用的:http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/和 – Zabba 2011-03-18 08:18:41

+0

它絕對看起來是。我會盡量在深夜停止提問。 – noazark 2011-03-18 16:08:01

回答

14

如何重寫組模型中的as_json方法?

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

gahhh。覆蓋!爲什麼要變得簡單。非常感謝你。 – noazark 2011-03-18 16:06:23

+0

真棒,謝謝你 – user3775217 2017-01-16 17:56:01

2

爲了防止質量分配,以下內容添加到你的模型:

attr_accessible :attr1, :attr2, :attr3 

其中attR1位,attR2位,attr3等等都是要允許屬性對於質量分配,該模型的其餘屬性不允許進行質量分配。

+0

該項目反對大規模的任務,但不是大衆寫作。所以,如果我使用'render:json => @ object'時不想顯示'private_attr','attr_accessable:private_attr'不起作用。 – noazark 2011-03-18 06:25:52