【发布时间】: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()
实现这一目标的最佳方法是什么?
更新
或者我怎样才能为每个文件夹实例中的笔记覆盖 create、new 和 函数。
【问题讨论】:
-
@folder.notes.create(user: current_user)是一种方式 -
Thanx @Sharagoz,但我想避免这个显式参数,因为文件夹已经知道它的用户。抱歉这么挑剔
-
如果笔记和它的文件夹总是属于同一个用户,那么
Note上的belongs_to :user关联是不是完全多余并且可以删除? -
我了解你@Sharagoz。但问题是没有任何文件夹的便笺可以存在..
-
好的,我明白了。如果文件夹存在,笔记和文件夹是否总是同一用户?如果是这种情况,您可以在模型层中创建回调,当文件夹存在时,用户关联将从文件夹中复制。
标签: ruby-on-rails ruby activerecord metaprogramming