ruby-on-rails - Rails 句柄连接表 UniqueViolation

标签 ruby-on-rails ruby postgresql upsert

我正在尝试将一行插入到我在此迁移中创建的连接表中(带有时间戳):

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/

相关文章:

html - CSS响应高度失败

Django 操作错误 : could not fork new process for connection

oracle - 如何将空间数据从 Oracle 移动到 Postgres

ruby-on-rails - 跨越从形式到更有趣的对象的 Rails 学习和开发障碍

ruby-on-rails - 在 Rails 中设置当前 Time.zone?

ruby-on-rails - 在 Ruby 和 Redis 中匹配现场玩家的最佳策略?

Ruby - 更新运行脚本

sql - 为范围内的缺失值补零

javascript - Rails 3 - 如何动态创建与参数关联的 html 元素 [ :id]?

ruby - 时间循环不循环