2011-11-19 1 views
2

완전 초급 : 레일에서모델에 연결된 양식 도우미에서 관련 모델의 필드를 참조하는 방법은 무엇입니까? 여기 레일에

:

는 전 모델 포스트, hasMany의 태그가 있습니다. 새 게시물을 만들 때 사용자가 게시물에 묶여있는 최대 5 개의 태그를 만들 수 있기를 바랍니다.

나는이 같은 새 게시물을 작성하는 양식을 설정 : 포스트 클래스는 tag_name 특성을 가지고 있지 않기 때문에

<%= form_for(@post) do |f| %> 
    <div class="field"> 
     <%= f.label :name %><br/> 
     <%= f.text_field :name %> 
    </div> 
    ... Some more of these 
    <div class="field"> <!-- I want this to refer to the name attribute of a Tag model--> 
     <%= f.label :tag_name %><br /> 
     <%= f.text_field :tag_name %> 
    </div> 
<% end %> 

은 물론,이 작동하지 않습니다. 이 작업을 수행하는 적절한 방법은 무엇입니까?

id: primary key 
post_id: foreign key to Post's primary key 
name: name of the tag 
+0

nested_attributes_for를 사용해 보셨습니까? 그것은 당신을 올바른 길로 인도 할 수 있습니다. –

답변

2

시도 후, 사용의 속성과 함께 양식에 accepts_nested_attributes_for

class Post < ActiveRecord::Base 
    has_many :tags 
    accepts_nested_attributes_for :tags 
end 

class Address < ActiveRecord::Base 
    attr_accessible :post_id 
    belongs_to :post 
end 

를 사용하여 : 그런

<% f.fields_for :tag, @post.address do |builder| %> 
    <p> 
    <%= builder.text_field :post_id %> 
    <p> 
<% end %> 

뭔가. 행운을 빌어 요.

관련 문제