1

同時に 2 つのオブジェクトを作成しようとしています。私が持っている最善のアプローチは、fields_for を使用することです。関係は has_many です。

モデル/場所.rb

  attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
  belongs_to :customer
  belongs_to :event

モデル/event.rb

  attr_accessible :locations_attributes
  has_many :locations, :dependent => :destroy
  accepts_nested_attributes_for :locations

フォームは次のとおりです。

<%= form_for(@event) do |f| %>
  ...
  <%= f.fields_for :locations do |e| %>
    <%= e.text_field :longitude %>
    <%= e.text_field :latitude %>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

フィールドが表示されません。このセクションのドキュメントhas_many に従ってい ます:locations は、フィールドが表示されるよりも単数形に変更しますが、locations_attributes の変更が許可されていないため、作成できません。

アップデート:

私がそれを単数なら。これをイベントモデルに変更します

  attr_accessible  :description, :title, :location_attributes

エラーはこんな感じ

app/controllers/events_controller.rb:60:in `new'
app/controllers/events_controller.rb:60:in `create'

私のコントローラーはこんな感じです

line 60: @event = Event.new(params[:event])
4

1 に答える 1

1

あなたのフォームでこれを行う必要があります:(場所ではなく場所)

<%= f.fields_for :location do |e| %>
    <%= e.text_field :longitude %>
    <%= e.text_field :latitude %>
<% end %>

そしてあなたのモデルevent.rbで

attr_accessible :description, :title, :locations_attributes(場所ではなく場所)

于 2013-01-05T17:22:03.700 に答える