【问题标题】:Looking for elegant way to assign ActiveRecord instance to two owners at once寻找优雅的方式将 ActiveRecord 实例一次分配给两个所有者
【发布时间】:2014-07-17 11:24:22
【问题描述】:

我的 Rails 应用中有以下模型关联结构:

class User < ActiveRecord::Base
  has_many :folders
  has_many :notes
end

class Folder < ActiveRecord::Base
 belongs_to :user
 has_many :notes
end

class Note < ActiveRecord::Base
  belongs_to :user
  belongs_to :folder
end

我想要打电话

@folder.notes.create()

将注释同时分配给文件夹和文件夹所有者。

换句话说,而不是

@folder = current_user.folders.first
...
@note = Note.new    
@folder.notes << @note
current_user.notes << @note

我只想

@folder.notes.create()

实现这一目标的最佳方法是什么?


更新

或者我怎样才能为每个文件夹实例中的笔记覆盖 createnew 函数。

【问题讨论】:

  • @folder.notes.create(user: current_user) 是一种方式
  • Thanx @Sharagoz,但我想避免这个显式参数,因为文件夹已经知道它的用户。抱歉这么挑剔
  • 如果笔记和它的文件夹总是属于同一个用户,那么Note上的belongs_to :user关联是不是完全多余并且可以删除?
  • 我了解你@Sharagoz。但问题是没有任何文件夹的便笺可以存在..
  • 好的,我明白了。如果文件夹存在,笔记和文件夹是否总是同一用户?如果是这种情况,您可以在模型层中创建回调,当文件夹存在时,用户关联将从文件夹中复制。

标签: ruby-on-rails ruby activerecord metaprogramming


【解决方案1】:

我找到了解决方案,感谢@Sharagoz 为我指明回调方向!

after_add 回调可以解决问题。

这是我所做的更改:

class Folder < ActiveRecord::Base
  belongs_to :user
  has_many :notes, after_add: :add_to_user

  def add_to_user(note)
    if(self.user)
      self.user.notes << note
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多