2011-03-07 2 views
1

포스트 모델건물 복잡한 형태와 관계

class Post < ActiveRecord::Base 

    attr_accessible :user_id, :title, :cached_slug, :content 
    belongs_to :user 
    has_many :lineitems 


    def lineitem_attributes=(lineitem_attributes) 
    lineitem_attributes.each do |attributes| 
     lineitems.build(attributes) 
    end 
    end 

포스트보기 : 나는 현재 몇 가지 코드 및보고 railscasts와 함께 연주하고 컨트롤러

12 def new 
13  @user = current_user 
14  @post = @user.posts.build(params[:post]) 
15  3.times {@post.lineitems.build} 
16 end 
17 
18 def create 
19  debugger 
20  @user = current_user 
21  @post = @user.posts.build(params[:post]) 
22  if @post.save 
23  flash[:notice] = "Successfully created post." 
24  redirect_to @post 
25  else 
26  render :action => 'new' 
27  end 
28 end 

에서

<% form_for @post do |f| %> 
    <%= f.error_messages %> 
    <p> 
    <%= f.label :title %><br /> 
    <%= f.text_field :title %> 
    </p> 
    <p> 
    <%= f.label :cached_slug %><br /> 
    <%= f.text_field :cached_slug %> 
    </p> 
    <p> 
    <%= f.label :content %><br /> 
    <%= f.text_area :content, :rows => 3 %> 
    </p> 
    <% for lineitem in @post.lineitems %> 
    <% fields_for "post[lineitem_attributes][]", lineitem do |lineitem_form| %> 
    <p> 
     Step: <%= lineitem_form.text_field :step %> 
    </p> 
    <% end %> 
    <% end %> 
    <p><%= f.submit %></p> 
<% end %> 

. 나는 73 세이며이 양식을 저축하는 것에 대해 질문이 있습니다.

나는 코드를 붙여 넣었으며 railscasts 73을 따라갔습니다. 내 코드는 다른 포스트 관계와 관련하여 20 ~ 23 행 주변에서 약간 다릅니다. 디버거를 사용하면 @post에는 user_id와 post 값만 있습니다. params에는 lineitem_attributes가 있습니다. lineitems 저장되지 않습니다.

광고 항목을 포함하여 게시물을 어떻게 작성합니까?

답변

1

이전의 철도 대다수 중 많은 부분이 현재 구형입니다. 요즘이 작업을 수행하는 표준 방법은 중첩 된 특성을 사용하는 것입니다. 이 주제에 관한 레일 캐스트는 Part 1part 2입니다. 나는 스크린 캐스트는 코드가 많이 간단하게 될 것이라는 점을 제외하고는 적용되지 않는 추가 할 수 많은 없다 :

class Post < ActiveRecord::Base 

    attr_accessible :user_id, :title, :cached_slug, :content 
    belongs_to :user 
    has_many :lineitems 

    accepts_nested_attributes_for :lineitems 
end 

이 보호 된 속성으로 어떻게 작동하는지 나는 즉석 기억할 수 있지만, 당신이해야 할 수도 있습니다 add : lineitems_attributes to attr_accessible

+0

답변에 뭔가가 수정되었습니다. 그렇지 않으면, 이것은 내가 찾고 있었던 해답이다. –