0

I have has_many_through relationship:

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

When I create the record, the join table (schedule_tasks) record that's created only populates the bare minimum fields to make the join, in this case, :schedule_id and :task_id, I need an additional field - :day_id filled as well (this field is also in the Task model, but right now this is how I need to do it:

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

Is there a simpler way to do this?

fatfrog
  • 2,118
  • 1
  • 23
  • 46

1 Answers1

0

I normally stay away from callbacks as they can result in very messy spaghetti logic, but this seems to be a decent use case.

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
fylooi
  • 3,840
  • 14
  • 24
  • I tried adding that, but it does not seem to be executing? SQL (0.1ms) INSERT INTO `schedule_tasks` (`schedule_id`, `task_id`, `created_at`, `updated_at`) VALUES (1, 105, '2015-04-27 17:21:54', '2015-04-27 17:21:54') (5.8ms) COMMIT – fatfrog Apr 27 '15 at 17:23
  • Looks like `self` is needed to force AR to recognize it as a method call instead of a local instance variable. http://stackoverflow.com/questions/10127393/why-use-self-to-access-activerecord-rails-model-properties/10127425#10127425 – fylooi Apr 27 '15 at 17:28