Rails - 在 join table 中使用附加参数构建关联记录
Rails - build associated record with additional params in join table
我有 has_many_through 关系:
class Schedule < ActiveRecord::Base
has_many :schedule_tasks
has_many :tasks, :through => :schedule_tasks
class Task < ActiveRecord::Base
has_many :schedule_tasks
has_many :schedules, :through => :schedule_tasks
当我创建记录时,创建的连接 table (schedule_tasks) 记录仅填充最低限度的字段以进行连接,在这种情况下,:schedule_id 和:task_id,我还需要一个额外的字段 - :day_id 填充(这个字段也在任务模型中,但现在我需要这样做:
def create
@schedule = Schedule.find(task_params['schedule_id'])
@task = @schedule.tasks.create(task_params)
@schedule_task = @schedule.schedule_tasks.where(task_id: @task.id, schedule_id: @schedule.id).first
@schedule_task.day_id = @task.day_id
@schedule_task.save
redirect_to @schedule
end
有更简单的方法吗?
我通常远离 callbacks,因为它们会导致非常混乱的意大利面条逻辑,但这似乎是一个不错的用例。
class ScheduleTask < ActiveRecord::Base
belongs_to :task
belongs_to :schedule
before_save :set_day_id
def set_day_id
self.day_id = task.day_id
end
end
我有 has_many_through 关系:
class Schedule < ActiveRecord::Base
has_many :schedule_tasks
has_many :tasks, :through => :schedule_tasks
class Task < ActiveRecord::Base
has_many :schedule_tasks
has_many :schedules, :through => :schedule_tasks
当我创建记录时,创建的连接 table (schedule_tasks) 记录仅填充最低限度的字段以进行连接,在这种情况下,:schedule_id 和:task_id,我还需要一个额外的字段 - :day_id 填充(这个字段也在任务模型中,但现在我需要这样做:
def create
@schedule = Schedule.find(task_params['schedule_id'])
@task = @schedule.tasks.create(task_params)
@schedule_task = @schedule.schedule_tasks.where(task_id: @task.id, schedule_id: @schedule.id).first
@schedule_task.day_id = @task.day_id
@schedule_task.save
redirect_to @schedule
end
有更简单的方法吗?
我通常远离 callbacks,因为它们会导致非常混乱的意大利面条逻辑,但这似乎是一个不错的用例。
class ScheduleTask < ActiveRecord::Base
belongs_to :task
belongs_to :schedule
before_save :set_day_id
def set_day_id
self.day_id = task.day_id
end
end