2013-03-06 4 views
1

Ruby on Rails를 시작했고 has_many :through 연관 문제가 발생했습니다.레일스 연관 has_many : through

class Phrase < ActiveRecord::Base 
    attr_accessible :event_type_id, :template_pieces 

    belongs_to :event_type 
    has_many :phrases_pieces 
    has_many :template_pieces, :through => :phrases_pieces 
end 

class TemplatePiece < ActiveRecord::Base 
    attr_accessible :datatype, :fixed_text, :name 

    has_many :phrase_pieces 
    has_many :phrases, :through => :phrases_pieces 
end 

class EventType < ActiveRecord::Base 
    attr_accessible :name 

    has_many :phrases 
end 

class PhrasesPiece < ActiveRecord::Base 
    attr_accessible :order, :phrase_id, :template_piece_id 

    belongs_to :phrase 
    belongs_to :template_piece 
end 

그리고 나는 그것의 기본 양식을 편집, 새로운 문구를 만들려고 해요 : 내가 사용

모델은

<%= form_for(@phrase) do |f| %> 
    <% if @phrase.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@phrase.errors.count, "error") %> prohibited this phrase from being saved:</h2> 

     <ul> 
     <% @phrase.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    Select the event type: 
    <%= collection_select(:phrase, :event_type_id, EventType.all, :id, :name) %> 
    Select the phrases to be used: 
    <%= collection_select(:phrase, :template_pieces, TemplatePiece.all, :id, :name) %> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

내가 먼저 질량에 문제가 있었다 과제,하지만 구문 모델에 attr_accessible :template_pieces을 추가하는 것을 수정했습니다. 그것이 정확한 수정 방법인지 확신 할 수는 없지만 적어도 보호 속성을 지정할 수는 없다는 불평은 멈추었습니다. "1"에 대한

정의되지 않은 메서드`각각 ': 나는 좀 생각

문자열

을 인해 일어나는 새로운 문구를 제출할 때

지금, 나는 다음과 같은 오류를 받고 있어요 사실 주어진 문구에 대해 많은 template_pieces가 있어야한다는 사실이지만, 현재는 한 번에 하나만 제출할 수 있습니다. 그래서 그것은 단지 하나를 발견하고 그것을 반복하고 실패합니다.

어떻게 수정하겠습니까? 데이터베이스에 has_many :through으로 모델을 입력하는 더 좋은 방법이 있습니까? 수동으로해야합니까 (기본 컨트롤러 @phrase = Phrase.new(params[:phrase]).

감사합니다.

+0

오류와 함께 전체 스택 추적을 갖는 것이 유용 할 것입니다. – adamdunson

+0

표시되는 오류 페이지는 다음과 같습니다. [페이지 캡처] (https://www.dropbox.com/s/62dat91bx4dh2jg/error_msg.png?m) – snowingheart

답변

0

당신은 중첩 된 속성을 포장하기 위해 fields_for 도우미를 사용한다 :

fields_fordocumentation

<%= f.fields_for :template_pieces do |template_f| %> 
    <%= template_f.collection_select, :event_type_id, EventType.all, :id, :name %> 
    Select the phrases to be used: 
    <%= template_f.collection_select, :template_pieces, TemplatePiece.all, :id, :name %> 
<% end %> 

참조.

+0

특정 구문을 사용하면 오류가 발생합니다. 'collection_select' 후에 쉼표를 제거하려고 시도했는데 제출 후 다음과 같이 응답합니다 : 'TemplatePiece (# 70324553021400) 예상, 배열 있음 (# 10676920)' – snowingheart