0

has_one (:class_name オプションを使用) と belongs_to リレーションを使用して、2 つの子オブジェクトに値を設定するフォームを作成しようとしています。しかし、フォームから値を入力して送信すると、異なる値を入力しても、両方の子オブジェクトが同じ値になります。

私はこの2つのモデルを持っています。(上記の 2 つの子オブジェクトは、クラス名が「Place」である「origin」と「destination」を示します)

class Route < ActiveRecord::Base
  attr_accessible :name, :destination_attributes, :origin_attributes                                            
  has_one :origin, :class_name=>"Place"
  has_one :destination, :class_name=>"Place"
  accepts_nested_attributes_for :origin, :destination
end

class Place < ActiveRecord::Base                                                                                                                                              
  attr_accessible :address, :lat, :lng, :name, :route_id
  belongs_to :route, :foreign_key => "route_id"
end

そして、以下のようにパーシャルを使ってフォームを作りました。

ルート/_form.html.erb

<%= form_for(@route) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
    <br />
    <%= render :partial => "places/nested_places_form", :locals => {record_name: :origin, place_object: @route.origin, parent_form: f} %>
    <br />
    <%= render :partial => "places/nested_places_form", :locals => {record_name: :destination, place_object: @route.destination, parent_form: f} %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

場所/nested_places_form.html.erb

 <%= parent_form.fields_for record_name, place_object  do |t| %>                                                                                                               
  <%= record_name %>

  <% if place_object.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@place.errors.count, "error") %> prohibited this place from being saved:</h2>

      <ul>
      <% @place.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= t.label :name %><br />
    <%= t.text_field :name %>
  </div>
  <div class="field">
    <%= t.label :lat %><br />
    <%= t.text_field :lat %>
  </div>
  <div class="field">
    <%= t.label :lng %><br />
    <%= t.text_field :lng %>
  </div>
<% end %>                                                                                                                                                                     

前述したように、空白に異なる値を入力してフォームから送信しても、出発地と目的地の属性は常に同じになります。

どうすればこれを機能させることができますか?

4

1 に答える 1

0

どういうわけか、データベース内の出発地と目的地を区別する必要があります。両方が同じクラスを持ち、同じテーブルに格納されている場合、それらを区別するものは何もありません。既存の関係を変更したくない場合は、これに STI を使用し、出発地と目的地を異なるクラスにする必要がある場合があります。

class OriginPlace < Place
end

class DestinationPlace < Place
end

class Route < ActiveRecord::Base
  ...
  has_one :origin, :class_name=>"OriginPlace"
  has_one :destination, :class_name=>"DestinationPlace"
  ...
ene

typeこれには、places テーブルにフィールドが必要です。

于 2012-04-29T17:18:11.273 に答える