Rails嵌套模型表单,带有has_many通过关系和构建调用

时间:2009-12-22 22:25:41

标签: ruby-on-rails

我正在构建一个单页表单,它将创建一个模型及其关系。我已经浏览了网络上的大量资源以及Railscasts上的复杂表单系列,但似乎无法找到我的问题的解决方案。

这就是我所拥有的。

class Campaign < ActiveRecord::Base
  has_many :artwork_groups
  has_many :artwork_locales, :through => :artwork_groups

  accepts_nested_attributes_for :artwork_groups
  accepts_nested_attributes_for :artwork_locales
end

class ArtworkGroup < ActiveRecord::Base
  belongs_to :campaign
  has_many :artwork_locales
end

class CampaignsController < ApplicationController
  def new    
    @campaign = Campaign.new
    @locales = Locale.all

    # Build the artowrk groups and locales for the new campaign
    2.times do
      @campaign.artwork_groups.build do |ag|
        @locales.each do |locale|
          ag.artwork_locales.build(:locale_id => locale.id)
        end
        logger.debug ag.artwork_locales
      end
    end

    @games = GameVersion.all(:order => "game_key").group_by(&:game_family).sort_by{|k| k.first.name }

    respond_to do |format|
      format.html
    end
  end

在我看来,我有以下内容(删除了标记):

<% form_for @campaign, :html => { :multipart => true } do |campaign| %>

  <%= campaign.error_messages %>
  <%= flash[:campaign_wizard] %>

  <%= campaign.label :title %>
  <%= campaign.text_field :title %>

  <%= campaign.label :url %>
  <%= campaign.text_field :url %>

  <%= campaign.label :start_date %>
  <%= campaign.text_field :start_date, {:class=>"datetimepicker"} %>

  <%= campaign.label :end_date %>
  <%= campaign.text_field :end_date, {:class=>"datetimepicker"} %>

  <% campaign.fields_for :artwork_groups do |aw| %>

    <%= aw.label :name, "Artwork Group Name"  %>
    <%= aw.text_field :name %>

    <% aw.fields_for :artwork_locales do |al| %>

      <%= al.label :locale_id %>
      <%= al.text_field :locale_id %>

      <%= al.label :language %>
      <%= al.text_field :language %>

      <%= al.label :upstate %>
      <%= al.text_field :upstate %>

    <% end %>

  <% end %>

  <%= campaign.submit 'Save Campaign &amp; Publish' %>  

<% end %>

我在我的视图中获得了2个艺术作品组部分,但我每个艺术作品组只获得一个艺术作品区域。我期待每个语言环境都有一个我已经加载了。我假设这是has_many through关系或我的控制器中的嵌套构建调用的问题。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

您是否尝试将accepts_nested_attributes_for :artwork_locales添加到ArtworkGroup