fields_for通过关系轨道has_many 3.



我在让下面的代码工作时遇到问题。

  class Page < ActiveRecord::Base
     has_many :page_parts, :through => :page_parts_pages
     has_many :page_parts_pages
     accepts_nested_attributes_for :page_parts, :allow_destroy => true
     accepts_nested_attributes_for :page_parts_pages, :allow_destroy => true
  end
  class PagePart < ActiveRecord::Base
     has_many :page_parts_pages
     has_many :pages, :through => :page_parts_pages
  end
  class PagePartsPage < ActiveRecord::Base
     belongs_to :page
     belongs_to :page_part
  end

表结构:-

  pages
      id, title
  pages_parts
      id, title
  page_parts_pages
      id, page_id, page_part_id

查看代码

  <% page_fragment.each do |k,v| %>
     <%  if v.nil? or v.blank? or v.empty? %>
       <% parts =  f.object.page_parts.build if f.object.page_parts.blank? %>
       <%= f.fields_for :page_parts, parts do |p| %>
         <%= render 'page_part_form_field', :f => p %>
       <% end %>
      <% else  %>
       <% parts_page =  f.object.page_parts_pages.build if   f.object.page_parts_pages.blank? %>
    <%= f.fields_for :page_parts_pages, parts_page do |p| %>
      <%= render 'page_part_page_form_field', :f => p %>
    <% end %>
  <% end %>
<% end %>

实际上,情况是,我必须根据条件显示page_parts和page_parts_pages字段。如果满足条件,则显示page_parts其他字段page_parts_pages的字段。

对于新操作工作得很好,但对于编辑操作,它无法正确显示。

任何帮助都非常感谢。

提前致谢

您正在以以下形式创建新page_parts:

parts =  f.object.page_parts.build if f.object.page_parts.blank?
parts_page =  f.object.page_parts_pages.build if   f.object.page_parts_pages.blank?

"build"创建新对象(但它不会将它们保留在数据库中)。所以,难怪它适用于新版,但不适用于编辑。你可以试试这个:

  <% page_fragment.each do |k,v| %>
     <%  if v.blank? %>
       <%= f.fields_for :page_parts do |p| %>
         <%= render 'page_part_form_field', :f => p %>
       <% end %>
      <% else  %>
    <%= f.fields_for :page_parts_pages do |p| %>
      <%= render 'page_part_page_form_field', :f => p %>
    <% end %>
  <% end %>
<% end %>

Rails API有很好的forms_for和其他表单助手的文档。

相关内容

  • 没有找到相关文章

最新更新