深层嵌套属性和attr_accessible

时间:2013-06-06 05:17:09

标签: ruby-on-rails ruby-on-rails-3 activerecord

使用params:

{"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 个答案:

答案 0 :(得分:2)

我的猜测:在Gallery模型中。

从嵌套哈希的外观来看,media_items_attributes位于gallery_attributes部分下。所以你需要把它放在那个级别。

答案 1 :(得分: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