Rails:belongs_to&accepts_nested_attributes_for,polymorphic

uca*_*ion 2 ruby ruby-on-rails

我正在开发我的第一个Rails项目,我有以下模型关系:

class Profile < ActiveRecord::Base
  belongs_to :identifiable, polymorphic: true
  accepts_nested_attributes_for :students

class Student < ActiveRecord::Base
  has_one :profile, as: :identifiable
  attr_accessible :profile
Run Code Online (Sandbox Code Playgroud)

相关的控制器是:

class StudentsController < ApplicationController
  def new
    @student = Student.new
  end

  def create
    @student = Student.new(params[:student])
    if @student.save
      redirect_to root_path
    else
      render 'new'
   end
  end
end
Run Code Online (Sandbox Code Playgroud)

class ProfilesController < ApplicationController
  def new
    @profile = Profile.new
  end

 def create
    @profile = Profile.new(params[:profile])
    @profile.save
 end
end
Run Code Online (Sandbox Code Playgroud)

我要做的是Student使用以下形式创建一个新的,它位于students\new.html.erb:

<h1>Create a new Student Account</h1>
<div class="row">
  <div class="span6 offset3">
  <%= form_for(@student) do |f| %>
    <%= render 'shared/error_messages' %>
    <%= f.fields_for :profile, @profile do |builder| %>
      <%= builder.label :name %>
      <%= builder.text_field :name %>

      <%= builder.label :email %>
      <%= builder.text_field :email %>

      <%= builder.label :password %>
      <%= builder.password_field :password %>

      <%= builder.label :password_confirmation, "Confirmation" %>
      <%= builder.password_field :password_confirmation %>
    <% end %>
  </div>
</div>
  <p><%= f.submit "Submit", class: "btn btn-large btn-primary" %></p>
<% end %>
Run Code Online (Sandbox Code Playgroud)

当我尝试提交表单时收到以下错误消息:No association found for name 'students'. Has it been defined yet?我做错了什么?提前致谢.

cde*_*ers 6

为了使模型接受另一个模型的嵌套属性,需要声明与另一个模型的关联.在Profile你有accepts_nested_attributes_for :students,但没有定义相应的关联(例如has_many :students),这就是你得到那个特定错误的原因.但是,在您的情况下,这种关联是不正确的.

通常,如果模型A接受对于嵌套模型属性B,无论是A has_many BA has_one B.在你的情况下,你有A belongs_to B.一个更好的设计

class Profile < ActiveRecord::Base
  belongs_to :identifiable, polymorphic: true

class Student < ActiveRecord::Base
  attr_accessible :profile_attributes
  has_one :profile, as: :identifiable
  accepts_nested_attributes_for :profile
Run Code Online (Sandbox Code Playgroud)