0

我在尝试使关联起作用时遇到了一些麻烦。

我的模型看起来像:

广告.rb

class Advertise < ActiveRecord::Base

  belongs_to :user
  belongs_to :country

  has_many :targets
  # has_many :hss, :through => :targets

  validates :description, :presence => true
  validates :url, :presence => true
  validates :country_id, :presence => true
  validates :kind, :presence => true

  attr_accessible :description, :hits, :url, :active, :country_id, :kind

  KINDS = {
    '1' => 'Commoditie',
    '2' => 'Service',
  }

  HS = {
    '1' => 'Section',
    '2' => 'Chapter',
    '4' => 'Heading',
    '5' => 'SubHeading 1',
    '6' => 'SubHeading 2',
  }
end

hs.rb

class Hs < ActiveRecord::Base
  attr_accessible :code, :kind

  has_many :targets
  has_many :advertises, :through => :targets
end

目标.rb

class Target < ActiveRecord::Base
  attr_accessible :advertise_id, :hs_id

  belongs_to :advertise
  belongs_to :hs
end

advertises_controller.rb

  def new
    @advertise = Advertise.new

    @countries = Country.all
  end

  def create
    @advertise = current_user.advertises.build(params[:advertise])

    if @advertise.save
      flash[:notice] = 'Advertise created with successful'
      redirect_to root_path
    else
      render :new
    end
  end

用于form创建新广告。

/advertises/new.html.haml

%table.table.table-striped
  %tr
    %td{:colspan => 2}= advertise.input :url, :required => true
  %tr
    %td{:colspan => 2}= advertise.input :description, :required => true, :as => :text, :input_html => { :cols => 50, :rows => 3 }
  %tr
    %td{:colspan => 2}= advertise.input :country_id, :collection => @countries, :as => :select, :label => 'Origin', :required => true
  %tr
    %td{:colspan => 2}= advertise.input :kind, :collection => Advertise::KINDS.map(&:reverse), :as => :select, :label => 'Type', :required => true
  %tr
    %td{:colspan => 2}= advertise.input_field :active, as: :boolean, inline_label: 'Active'

  =fields_for :targets do |target|
    %tr
      %td= select_tag :hs_kind, options_for_select(Advertise::HS.map(&:reverse).insert(0,'') )
      %td= target.select :hs_id, ''

hash参数:

[3] pry(#<AdvertisesController>)> params
=> {"utf8"=>"✓",
 "authenticity_token"=>"fOdn4NYLg/4HXruWURZPf9DYVT4EQzbaTRTKZvX1ugY=",
 "advertise"=>
  {"url"=>"http://test.com",
   "description"=>"test",
   "country_id"=>"17",
   "kind"=>"2",
   "active"=>"1"},
 "hs_kind"=>"2",
 "targets"=>{"hs_id"=>"487"},
 "commit"=>"Create Advertise",
 "action"=>"create",
 "controller"=>"advertises"}

哈希对我来说似乎没问题,但它只创建Advertise,而不是targetadvertise关联创建。

有吗?也许是错误的模型关联。

提前致谢。

4

1 回答 1

1

尝试改变

=fields_for :targets do |target|

= advertise.fields_for :targets do |target|

并将以下内容添加到advertise.rb

accepts_nested_attributes_for :targets
attr_accessible :targets_attributes  # just add targets_attributes to attr_accessible

请注意,执行此操作时,没有目标的广告对象将不会显示目标字段。您必须构建一个与广告相关的新目标对象才能显示字段

# example: on the new action of the controller
@advertise = Advertise.new
@advertise.targets.build
于 2013-02-20T03:19:26.907 回答