1

accept_nested_attributes を使用してフォームにオブジェクトのフィールドを設定しようとしています。ただし、コントローラーで行う場合:

@device.update_attributes(params[:device])

私は得る:

ActiveRecord::UnknownAttributeError
"unknown attribute: device_id" 

ただし、関連のない他のモデルの属性である device_id は params に含まれません。パラメータは次のようなものです。

{"utf8"=>"✓",
 "authenticity_token"=>"Xja5GCNRutpZn2c4wKeSx0KO6sNEzh09kWmPQ0/0Hys=",
 "id"=>"5",
 "device"=>{"routes_attributes"=>{"0"=>{"name"=>"",
 "origin_attributes"=>{"name"=>"",
 "lat"=>"",
 "lng"=>""},
 "destination_attributes"=>{"name"=>"",
 "lat"=>"",
 "lng"=>""}}}},
 "commit"=>"Create Device"}

原因として考えられること。これが私のコードです。

見る

<%= form_for @device, :url => {:action => "do_compose"}, :method => :post do |f| %>
  <div class="field">
     <%= select_tag(:id, options_for_select( Device.all.collect{|d| [d.name + "/" + d.get_driver().name, d.id] } ),:prompt=>"select a device") %>                                 
  </div>

  <div class="field">
    <%= render partial:"routes/nested_routes_form", locals: {route_object:@device.get_route(), parent_form:f} %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

コントローラ

  def do_compose
    @device = Device.find(params[:id])
    respond_to do |format|
      if @device.update_attributes(params[:device])
        format.html { redirect_to @device, notice: 'Device was successfully updated.' }
      else
        format.html { render action: comopse }
      end
    end
  end

モデル

  class Route < ActiveRecord::Base
    attr_accessible :name, :destination_attributes, :origin_attributes, :waypoints, :driver_id
    has_many :waypoints
    has_one :origin, :class_name=>"Origin"
    has_one :destination, :class_name=>"Destination"
    belongs_to :device
    accepts_nested_attributes_for :origin, :destination, :waypoints
  end

  class Device < ActiveRecord::Base
    attr_accessible :id, :name, :password
    attr_accessible :device_driver_bind_attributes, :drivers_attributes, :routes_attributes, :current_location_attributes
    has_many :drivers, through: :device_driver_bind
    has_many :device_driver_bind, dependent: :destroy
    has_one :current_location, :class_name => "CurrentLocation"
    has_many :routes
    has_many :origins, through: :routes
    has_many :destinations, through: :routes
    has_many :waypoints, through: :routes
    accepts_nested_attributes_for :routes, :current_location, :device_driver_bind
  end 
4

2 に答える 2

0
ActiveRecord::UnknownAttributeError
"unknown attribute: device_id"

ルートの列が欠落していることが原因のようです。

accepts_nested_attributes_for :routesActiveRecord は、 を満たすために、これを で設定できることを期待していますbelongs_to :device

于 2012-06-18T13:57:29.473 に答える
0

これはselect_tagの問題である必要があります。これを試してください:

<%= f.select(:id, options_for_select( Device.all.collect{|d| [d.name + "/" + d.get_driver().name, d.id] } ),:prompt=>"select a device") %>  
于 2012-06-13T05:26:14.833 に答える