0

我正在尝试制作一个表单,通过 has_one (使用 :class_name 选项)和 belongs_to 关系为两个子对象设置值。但是,当我通过表单输入和提交值时,即使我输入不同的值,两个子对象也具有相同的值。

我有这两个模型。(上面的两个子对象表示类名为“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位置表中的字段。

于 2012-04-29T17:18:11.273 回答