[英]Rails best practice for creating a model during the creation of a separate model
[英]Rails: filling in model attributes during creation
我在User和Task模型之間有多對多的關系。
任務可以有許多用戶,但它應該跟蹤其原始創建者(如果用戶通過@user.tasks.create
創建一個)。 我想知道我怎么能這樣做。
我必須在tasks表中創建一個名為“creator”的新列字段。 然后,我可以通過以下方式初始化任務:
@user.tasks.create(:creator=>@user)
有沒有辦法不必添加參數,因為創建者將永遠是實例化任務的用戶。
謝謝!
編輯
我的用戶模型有:
has_many :taskization
has_many :tasks, :through => :taskization
我的任務模型有:
has_many :taskization
has_many :users, :through => :taskization
我傾向於將creator屬性放在連接模型中(Taskization)。 如果你這樣做(比如說,通過這次遷移),
class AddCreatorIdToTaskizations < ActiveRecord::Migration
def change
add_column :taskizations, :creator_id, :integer
end
end
然后,您可以向taskization.rb添加回調
before_create do |taskization|
taskization.creator_id = taskization.user_id
end
那可以讓你到達你想要的地方。 如果您確定創建者屬性所屬的位置,您可以在任務模型中執行類似的回調,但我沒有完全想到這一點。
聽起來你正在指示'original_creator'是Task的一個屬性。 對於每個任務記錄,您希望跟蹤最初創建它的用戶。
所以,建模看起來像你需要兩個:
# return the User object of the original task creator
@original_creator_user = @task.original_creator
以及
# get all users of this task
@users = @task.users
上班。
這需要Task
對象和User
對象之間的兩種不同關系。
class User < ActiveRecord::Base
# tasks for this user
has_many :taskization
has_many :tasks, :through => :taskization
# tasks this user was the original creator of
has_many :created_tasks, :class_name => "Task"
end
class Task < ActiveRecord::Base
# users of this task
has_many :taskization
has_many :users, :through => :taskization
# user who originally created this class
belongs_to :original_creator, :class_name => "User"
end
請注意,“創建者”關系不是:through
任務,它是兩個對象之間的直接關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.