我在使用以下代码时遇到问题。
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的字段。
它对新动作完全正常,但对于编辑操作,它无法正确显示。
非常感谢任何帮助。
提前致谢
答案 0 :(得分:0)
您正在以这种形式创建新的page_part:
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有很好的form_for和其他表单助手文档。