Rails:belongs_to& accepts_nested_attributes_for,polymorphic

时间:2012-10-09 01:04:33

标签: ruby-on-rails ruby

我正在开发我的第一个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

相关的控制器是:

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

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

 def create
    @profile = Profile.new(params[:profile])
    @profile.save
 end
end

我要做的是使用以下格式创建一个新的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 %>

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你的学生应该是单数吗?即:accepts_nested_attributes_for :student

编辑:此外,您的学生应该接受个人资料的嵌套属性,如果学生has_one个人资料,并且学生表格包含fields_for电话(我认为...)