【问题标题】:Nested attributes / form: Unpermitted params嵌套属性/形式:未经许可的参数
【发布时间】:2015-01-25 23:48:41
【问题描述】:

我一直在检查 active record nested attributes docsstrong params docs,但我的日志告诉我,所有权和图像仍然不允许使用:

User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
    Unpermitted parameters: ownership, image 

我的嵌套 form_for 有 3 个模型:

= form_for @murals do |f|

  = f.fields_for @ownerships do |owner|
    = owner.label "Artist"
    = owner.collection_select(:user_id, User.where(artist: true), :id, :first_name, { include_blank: "Pick an artist" })

  = f.hidden_field :latitude, id: 'lat'
  = f.hidden_field :longitude, id: 'long'

  = f.fields_for @images do |image|
    = image.label :file, 'Add Image'
    = image.file_field :file
    = image.file_field :file_cache, class: 'hidden'

  =f.submit 'Upload Mural', class: 'btn btn-primary upload-btn'

我的控制器(我也尝试过使用单个 x_attributes: [:xyz] 没有运气)

def create
    @image = current_user.murals.build(mural_params)
    if @image.save
      redirect_to :root
    else
      render :new
    end
  end

  private

    def mural_params
      params.require(:mural).permit(:longitude, :latitude,
                                    image_attributes: [:file, :file_cache ], 
                                    ownership_attributes: [:user_id]
                                   )
    end

图片.rb:

class Image < ActiveRecord::Base
  belongs_to :user
  belongs_to :mural

  mount_uploader :image, MuralUploader
end

所有权.rb

class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :mural
end

用户.rb:

class User < ActiveRecord::Base
  has_many :authentications, dependent: :destroy
  has_many :images
  has_many :ownerships
  has_many :murals, through: :ownerships

  validates :first_name, presence: true

  mount_uploader :avatar, AvatarUploader
end

壁画.rb:

class Mural < ActiveRecord::Base
  has_many :ownerships
  has_many :images
  has_many :users, through: :ownership
  accepts_nested_attributes_for :ownerships, :images
end

【问题讨论】:

  • 你能分享你的型号代码吗?
  • 看起来您的所有权关联是 has_many,如果是这种情况,请使用 ownerships_attributes: [:user_id]
  • @tyamagu2 添加了他们。
  • @mintuhouse 不能将它们复数化。

标签: ruby-on-rails parameters nested-forms nested-attributes


【解决方案1】:

您需要使用accepts_nested_attributes_for 启用嵌套属性更新。

class Mural < ActiveRecord::Base
  ...
  accepts_nested_attributes_for :images, :ownerships
  ...
end

更多详情请见http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

【讨论】:

  • 有,但仍然没有获得许可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多