0

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

  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 的字段。

它对于新操作非常有效,但对于编辑操作,它无法正确显示。

非常感谢任何帮助。

提前致谢

4

1 回答 1

0

您正在以这种形式创建新的 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 和其他表单助手的很好的文档。

于 2012-06-28T16:35:58.747 回答