我正在尝试将一行插入到我在此迁移中创建的连接表中(带有时间戳):
class CreateUserNewsItemJoinTable < ActiveRecord::Migration
def change
create_join_table :users, :news_items do |t|
t.timestamps
end
add_index :news_items_users, [:user_id, :news_item_id], unique: true
end
end
这就是我将 NewsItem 插入用户的方式:
@user.news_items << @news_item
第一次,插入成功。但是如果我再次插入相同的记录,它会显示 UniqueViolation。
如何进行相同的插入以更新时间戳,而不是抛出 UniqueViolation 错误?
最佳答案
你不想再次插入,你想更新连接表。
根据rails guides如果您完全需要使用连接表,它应该有自己的模型:
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).
因此,创建模型并使用 has_many_through。
然后您将能够:
item = UserNewsItem.find_by(news_id: x, user: y)
item.update_attribute(:updated_at, Time.now)
关于ruby-on-rails - Rails 句柄连接表 UniqueViolation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25640891/