2012-10-09 63 views
2

我的工作我的第一個Rails項目,和我有以下型號的關係:的Rails:belongs_to的&accepts_nested_attributes_for,多態

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以下ing形式,這是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?我在做什麼錯?提前致謝。

回答

6

爲了使模型接受另一個模型的嵌套屬性,則需要聲明與其他模型的關聯。在Profile中,您有accepts_nested_attributes_for :students,但沒有定義相應的關聯(例如has_many :students),這就是您遇到特定錯誤的原因。就你而言,這種關聯不是正確的,但是。

通常,如果模型A接受嵌套屬性爲模型B,無論是Ahas_manyBAhas_oneB。在你的情況下,你有Abelongs_toB。更好的設計是

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 
+0

修復它。謝謝! – ucarion

+0

也解決了我的問題thanx –

+0

有沒有辦法做同樣的配置文件形式,而不是學生? – Vla

1

你的學生應該是單數嗎?即:accepts_nested_attributes_for :student

編輯:另外,你的學生應該接受嵌套屬性的配置文件,如果學生HAS_ONE輪廓,與學生表格中包含有fields_for電話(我想...)

+0

即使有這種變化,我也會得到相同的錯誤信息。 – ucarion

相關問題