建立复杂的形式和关系

时间:2011-03-07 02:56:15

标签: ruby-on-rails associations

发布模型

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

发布视图:

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

来自控制器

 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

我正在玩一些代码并观看有轨电视播放。我现年73岁,对保存此表单有疑问。

我已经粘贴了一些代码并跟随railscasts 73。关于另一个帖子关系,我的代码在第20到第23行左右有点不同。使用调试器,@ post只有user_id和post值。 params包含lineitem_attributes。这些lineitems不会被保存。

如何构建包含lineitems的帖子?

1 个答案:

答案 0 :(得分: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

我不记得这是如何使用受保护的属性,但您可能需要添加:lineitems_attributes到attr_accessible

相关问题