Adv*_*ion 2 ruby ruby-on-rails nested-attributes ruby-on-rails-4
所以我对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"=>""}
-----
现在,我认为我不需要允许艺术家,因为它是一个哈希..即使我允许它,它也不会改变..任何想法?
好的,在#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 ])
| 归档时间: | 
 | 
| 查看次数: | 1935 次 | 
| 最近记录: |