ruby-on-rails - 为什么关联的模型会被触及?

标签 ruby-on-rails activerecord

我有 3 个模型:

class DeliveryMethod
  has_many :subscription_delivery_methods
  has_many :subscriptions, :through => :subscription_delivery_methods
end

class SubscriptionDeliveryMethod < ActiveRecord::Base
  belongs_to :subscription
  belongs_to :delivery_method
end

class Subscription < ActiveRecord::Base
  has_one :subscription_delivery_method
  has_one :delivery_method, :through => :subscription_delivery_method
end

我像这样将交付方式分配给订阅:

s.delivery_method = DeliveryMethod.find 1

当我像上面那样进行分配时,Rails 会更新 subscription_delivery_methods,这是预期的:

UPDATE subscription_delivery_methods SET delivery_method_id = 1, updated_at = '2011-10-27 09:11:23' WHERE subscription_delivery_methods.id = 2

但是当我执行 s.save! 时,它会触及 DeliveryMethod,这是意外且不需要的:

UPDATE delivery_methods SET updated_at = '2011-10-27 08:40:53' WHERE delivery_methods.id = 1

我在关联上尝试了各种 :readonly:touch 标志,以防止发生此更新。我没有成功。你们知道如何阻止它吗?

非常感谢。

最佳答案

也许自动保存

 has_one :delivery_method, :through => :subscription_delivery_method, :autosave => false

关于ruby-on-rails - 为什么关联的模型会被触及?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7913895/

相关文章:

ruby-on-rails - 再次返回使用 Rails 3 中的 Rails 2.3.5

ruby - 使用 RVM 使用 sinatra 应用程序加载 Active Record gem 时出错

ruby-on-rails - Rails 中的多个查询条件 - 如果它们存在。

ruby-on-rails - 如何在 Rails 控制台中输入多行

ruby-on-rails - 设计 user_root_path 在生产中得到 404'd 而不是 dev?

ruby-on-rails - 隐藏 ActiveRecord 模型中的属性

ruby-on-rails - rails/postgres : What is the best way to store list of phone numbers for one user

ruby-on-rails - 覆盖 database.yml 的策略

sql - 如何使用事件记录查询检查 Rails 5 中是否不存在记录?

mysql - 如何使用Rails手动连接MYSQL数据库?