通过accepts_nested_attributes更新belongs_to模型

时间:2014-01-13 04:17:31

标签: ruby-on-rails ruby

无法使用accepts_nested_attributes更新Product模型的state属性。这就是我发布的JSON的样子:

  

{“auth_token”=>“x”,“product”=> {“caption”=>“x”,“state_attributes”=> {“id”=>“1”}}, “ID”=> “中X”}

我需要做的就是改变引用状态。思考?


州模式

class State < ActiveRecord::Base
  has_many :products
end

产品型号

class Product < ActiveRecord::Base
  attr_accessible :state, :state_attributes
  belongs_to :state
  accepts_nested_attributes_for :state, :allow_destroy => false
end

产品控制器更新操作

def update

    product = Product.find_by_id( params[:id])

    if product && product.update_attributes(params[:product])
     respond_with(product, status: :updated, location: product)
    else
     respond_with(product.errors, status: :unprocessable_entity)
    end
 end

交易记录

Started PUT "/products/1170.json" for 127.0.0.1 at 2014-01-13 16:21:52 -0700
Processing by ProductsController#update as JSON
Parameters: {"auth_token"=>"x", "product"=>{"caption"=>"x", "state_attributes"=>{"id"=>"3"}}}, "id"=>"1170"}
WARNING: Can't verify CSRF token authenticity
User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'x' LIMIT 1
(0.1ms)  BEGIN
(0.3ms)  UPDATE "users" SET "last_sign_in_at" = '2014-01-13 23:20:46.614453', "current_sign_in_at" = '2014-01-13 23:21:52.251028', "sign_in_count" = 954, "updated_at" = '2014-01-13 23:21:52.251753' WHERE "users"."id" = 536
(6.5ms)  COMMIT
Product Load (0.5ms)  SELECT "products".* FROM "products" WHERE "products"."user_id" = 536 AND "products"."id" = 1170 LIMIT 1
(0.1ms)  BEGIN
State Load (0.2ms)  SELECT "states".* FROM "states" WHERE "states"."id" = 2 LIMIT 1
(0.5ms)  ROLLBACK
Completed 404 Not Found in 15ms

ActiveRecord::RecordNotFound (Couldn't find State with ID=3 for Product with ID=1170):
app/controllers/products_controller.rb:81:in `update'

Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
Rendered /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/actionpack-3.2.11/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (5.8ms)

1 个答案:

答案 0 :(得分:0)

正如@SergioAristizábal指出的那样,我试图重置关联状态而不是简单地更新id

  

您正在尝试重置关联状态的ID。我想你只想将一个州与产品联系起来,所以你应该只设置state_id属性。

有了这个,我更新了产品型号

class Product < ActiveRecord::Base
  attr_accessible :state_id, :state_attributes
  belongs_to :state
end

在json中传递状态id

{"auth_token"=>"x", "product"=>{"caption"=>"x","state_id"=>"1"}, "id"=>"x"}

一切都像魅力一样。谢谢@Sergio