首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >深层嵌套属性和attr_accessible

深层嵌套属性和attr_accessible
EN

Stack Overflow用户
提问于 2013-06-06 13:17:09
回答 2查看 892关注 0票数 2

使用params:

代码语言:javascript
复制
{"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

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-06 13:18:38

我猜:在Gallery模型中。

从您的嵌套散列的外观来看-- media_items_attributes位于gallery_attributes部分之下。所以你需要把它放在那个级别上。

票数 2
EN

Stack Overflow用户

发布于 2013-06-06 14:05:02

虽然你的问题已经解决了,但我还是回复给其他人,以获得清晰的想法:

下面是一个典型的场景:

如果模型定义如下:

user.rb

代码语言:javascript
复制
class User < ActiveRecord::Base
  attr_accessible  :name, :posts_attributes
  has_many :posts
  accepts_nested_attributes_for :posts
end

post.rb

代码语言:javascript
复制
class Post < ActiveRecord::Base
  attr_accessible :title, :content :user_id
end

那么一切都会好起来的。您可以将带有帖子的用户保存为嵌套属性。

以下是一个包含此场景的示例项目:

https://github.com/railscash/sample_change_user_role

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16954152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档