使用accepts_nested_attributes_for启用未允许的参数

时间:2013-12-09 12:14:11

标签: ruby-on-rails ruby ruby-on-rails-4 nested-attributes

所以我对Rails相当新,所以我可能会错过一些非常直接的东西..

我要做的是在创建Artist时创建Band

模型

band.rb

class Band < ActiveRecord::Base

  has_many :artists, dependent: :destroy

  accepts_nested_attributes_for :artists, allow_destroy: true

  ...

end

artist.rb

class Artist < ActiveRecord::Base

  belongs_to :band

  ...

end

控制器 band_controller.rb

class BandController < ApplicationController

  def new
    @band = Band.new
  end

  def create

    @band = Band.new(band_params)
    if @band.save
      ...
    else
      ...
    end

  end

  private

    def band_params
      params.require(:band).permit(:name, :hometown, :email, :artist, artist_attributes: [ :band_id, :first_name, :last_name, :email, :password, :password_confirmation ])
    end

end

查看

new.html.erb

<%= form_for(@band, url: "/artist/signup") do |f| %>

    <%= render 'shared/error_messages', object: f.object %>

    <%= f.fields_for :artist do |artist| %>
        <%= artist.text_field :first_name, :placeholder => "First Name", :maxlength => 100 %>
        <%= artist.text_field :last_name, :placeholder => "Last Name", :maxlength => 100 %>

        <%= artist.email_field :email, :placeholder => "Email Address", :maxlength => 255 %>
        <%= artist.password_field :password, :placeholder => "Password", :maxlength => 255 %>
        <%= artist.password_field :password_confirmation, :placeholder => "Confirm Password", :maxlength => 255 %>
    <% end %>

    <%= f.text_field :name, :placeholder => "Band Name", :maxlength => 100 %>
    <%= f.text_field :hometown, :placeholder => "Hometown", :maxlength => 100 %>
    <%= f.text_field :email, :placeholder => "Band Email", :maxlength => 100 %>
    <%= f.submit "Apply", class: "button" %>

<% end %>

我的开发日志正在写出:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "band"=>{"artist"=>{"first_name"=>"", "last_name"=>"", "email"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "name"=>"", "hometown"=>"", "email"=>""}, "commit"=>"Apply"}
-----
Unpermitted parameters: artist
{"name"=>"", "hometown"=>"", "email"=>""}
-----

现在,我认为我不需要允许艺术家,因为它是一个哈希..即使我允许它,它也不会改变.. 有什么想法吗?

2 个答案:

答案 0 :(得分:6)

好的,在#RubyOnRails的帮助下,我已经明白了。

我需要在BandController的新动作中构建艺术家

@band.artists.build

然后通过form_for(@band)进入视图,.fields_for :artist更改为.fields_for :artists,然后

  params.require(:band).permit(:name, :artist, artist_attributes: [ :band_id, :first_name ])

更改为

  params.require(:band).permit(:name, artists_attributes: [ :band_id, :first_name ])

答案 1 :(得分:0)

确保为您的乐队模型创建一个构建新动作,然后执行以下操作:

class BandController < ApplicationController
  def new
    @band = Band.new
    @band.artists.build
  end
end

您可能需要比一个乐队更多的嵌套艺术家属性:

class BandController < ApplicationController
  def new
    @band = Band.new
    3.times{@band.artists.build}
  end
end