2013-06-06 53 views
2

隨着PARAMS:深嵌套的屬性和attr_accessible

{"utf8"=>"✓", 
"_method"=>"put", 
"authenticity_token"=>"mZ0yUwkdUhi8JVeXfPPzukYr8QfmJjC0UptG3rS08Fo=", 
"commit"=>"Update Artist", 
"artist"=>{"name"=>"Test", 
"bio"=>"Some bio", 
"city"=>"Chicago", 
"state"=>"IL", 
"visible"=>"1", 
"published_at"=>"2013-06-05 20:23:48 UTC", 
"confirmed_at"=>"2013-06-05 12:00:00 UTC", 
"galleries_attributes"=>{"0"=>{"media_items_attributes"=>{"1370495729379"=>{"_destroy"=>"0", 
"mediable_type"=>"Image", 
"mediable_id"=>"45"}}}}}, 
"id"=>"test"} 

我已經在我的attr_accesible下面就我的藝術家模型

attr_accessible :media_items_attributes, :galleries_attributes, :name, :bio, :permalink, :billboard_image_id, :featured_at, :city, :state, :country, :latitude, :longitude, :visible, :confirmed_at, :published_at, :deleted_at, :genre_ids, as: :admin

,但我仍然會得到一個異常

Can't mass-assign protected attributes: media_items_attributes

我有在我的畫廊模式

attr_accessible :media_items_attributes

我困惑以下。

我在哪裏需要允許:media_items_attributes

class Gallery < ActiveRecord::Base 
    belongs_to :galeryable 
    attr_accessible :media_items_attributes 
    has_many :media_items, :as => :mediable 


    accepts_nested_attributes_for :media_items 

end 


class Artist < ActiveRecord::Base 


# Basic attibutes, associations and validations 
    # ---------------------------------------------------------------------------------------------------- 

    attr_accessible :media_items_attributes, :galleries_attributes, :name, :bio, :permalink, :billboard_image_id, :featured_at, :city, :state, :country, :latitude, :longitude, :visible, :confirmed_at, :published_at, :deleted_at, :genre_ids, as: :admin 

    # Validations 
    validates_presence_of :name, :bio, :city, :state 
    validate :publishable 

    # Geocode the artist based on city and state 
    geocoded_by :city_state 
    after_validation :geocode 

    has_many :genrefications, as: :genreable, dependent: :destroy 
    has_many :genres, through: :genrefications 
    has_many :galleries, as: :galleryable 
    accepts_nested_attributes_for :galleries 

end 

回答

2

我的猜測:在圖庫模型中。

從嵌套散列的外觀 - media_items_attributes位於gallery_attributes部分下。所以你需要把它放在那個水平上。

+0

我把它添加到畫廊模式。 –

+0

你能告訴我們更多的模型嗎? –

+0

你也有所有這些嵌套屬性的「accep_nested_attributes」嗎? –

1

雖然你的問題就解決了我回答這個爲他人獲得清晰的思路:

下面是一個典型場景:

如果模型定義,就像如下:

user.rb

class User < ActiveRecord::Base 
    attr_accessible :name, :posts_attributes 
    has_many :posts 
    accepts_nested_attributes_for :posts 
end 

post.rb

class Post < ActiveRecord::Base 
    attr_accessible :title, :content :user_id 
end 

那麼一切應該沒問題。您可以將帖子保存爲嵌套屬性。

下面是一個包含此方案的示例項目:

https://github.com/railscash/sample_change_user_role

+0

我的問題是更多 - 所以,帖子也接受屬性爲「評論」 –

+0

如果發佈,添加comments_attributes在attr_accessible和accepts_nested_attributes_for:評論應該是足夠 – Muntasim