Ruby on rails 如何通过关联直接更新has\u many\u中的联接模型?
我有一个Rails应用程序,有两种型号,还有第三种型号:Ruby on rails 如何通过关联直接更新has\u many\u中的联接模型?,ruby-on-rails,ruby,postgresql,activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,我有一个Rails应用程序,有两种型号,还有第三种型号: class Food < ApplicationRecord has_many :shopping_list_items has_many :users, through: :shopping_list_items end class ShoppingListItem < ApplicationRecord belongs_to :user belongs_to :food end cla
class Food < ApplicationRecord
has_many :shopping_list_items
has_many :users, through: :shopping_list_items
end
class ShoppingListItem < ApplicationRecord
belongs_to :user
belongs_to :food
end
class User < ApplicationRecord
has_many :shopping_list_items
has_many :foods, through: :shopping_list_items
end
对象看起来很好,直到我尝试保存它,当我遇到SQL错误时:
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: zero-length delimited identifier at or near """"
LINE 1: ...$1, "updated_at" = $2 WHERE "shopping_list_items"."" IS NULL
^
: UPDATE "shopping_list_items" SET "priority" = $1, "updated_at" = $2 WHERE "shopping_list_items"."" IS NULL):
我想它是在抱怨没有主键吧?不知道如何解决这个问题,因为rails文档说联接表不应该有主键列
我使用如下迁移创建了中间表:
create_table :shopping_list_items, id: false do |t|
t.belongs_to :user
t.belongs_to :food
t.string :priority
t.integer :position
t.timestamps
end
在本例中,购物列表项不是rails文档所指的联接表。在表中添加一个id列,所有这些都会起作用。因为您使用的
具有许多彻底的关联
,并且可以通过更新模型来存储其他数据,所以您应该在其中有一个主键。
create_table :shopping_list_items, id: false do |t|
t.belongs_to :user
t.belongs_to :food
t.string :priority
t.integer :position
t.timestamps
end