嵌套属性/表单:未经许可的参数

时间:2015-01-25 23:48:41

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

我已经查看了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

Image.rb:

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

  mount_uploader :image, MuralUploader
end

Ownership.rb

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

User.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

Mural.rb:

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

1 个答案:

答案 0 :(得分:0)

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

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

有关详细信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html