2012-10-09 6 views
2

내가 처음으로 레일 프로젝트에서 일하고 있어요, 나는 다음과 같은 모델의 관계가 있습니다레일 : 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을 생성하는 것입니다. No association found for name 'students'. Has it been defined yet? 내가 잘못 뭐하는 거지 : 나는 양식을 제출하려고 할 때 다음과 같은 오류 메시지가납니다

<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 %> 

: students\new.html.erb에 양식을 보내고? 미리 감사드립니다.

답변

6

을 중첩 특성을 받아 들여야한다 모델에서 다른 모델에 대한 중첩 된 특성을 허용하려면 다른 모델과의 연관성을 선언해야합니다. Profile에는 accepts_nested_attributes_for :students이 있지만 이에 해당하는 연관성이 정의되어 있지 않습니다 (예 : has_many :students). 따라서 특정 오류가 발생합니다. 그러나 귀하의 경우이 협회는 정확하지 않을 수 있습니다.

일반적으로 모델 A는 모델 B의 속성을 중첩 받아들이는 경우 중 하나 Ahas_manyB 또는 has_oneBA. 귀하의 경우에는 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

또한 내 문제를 해결했습니다 –

+0

학생 대신 프로필 양식을 사용하는 방법이 있습니까? – Vla

1

학생이 단수이어야합니까? 예 : accepts_nested_attributes_for :student

편집 : 학생 has_one 프로파일 및 학생 양식은 fields_for 전화가 포함되어있는 경우 또한, 당신의 학생은 위해서는 (I 생각을 ...), 프로파일에 대한

+0

이더라도 동일한 오류 메시지가 나타납니다. – ucarion

관련 문제