开发者

Duplicate activerecords associated from one model to another

So I have a Task model, a Ticket model and a Category model.

Category has_many Tasks Ticket has_many Tasks Category has_many Tickets Ticket belongs_to Category Task belongs_to Ticket Task belongs_to Category

The Tasks that are associated to a Category are the default Tasks for a Ticket when the Category is linked to a Ticket. So I need the Tasks that are associated to a Category to be duplicated and associated to the Ticket when a Category is selected for the Ticket.

I'm wondering if I can do something like this in my Ticket model:

  after_create :duplicate_tasks_to_ticket
  after_update :duplicate_tasks_to_ticket

  def duplicate_tasks_to_ticket
    if self.tasks.blank?
      f开发者_如何学Goor task in self.category.tasks.all
        new_task = Task.new
        new_task.name = task.name
        new_task.ticket_id = self.id
        new_task.save
      end
    end
  end

Right now this doesn't throw any errors but it doesn't do anything. Any help would be greatly appreciated. Thanks!


If you are already associating them to the category, why do they need to be associated to the ticket also? If you need the granularity of being tied to a ticket, then just use that association to get all tasks under a category. Tieing them to both just make site complicated. Now, if you absolutely need to tie them to both, you should create an assignment table for that, which stores category_id, task_id. Another assignment table for ticket_id, task_id. Then keep the task as one record, as supposed to duplicating data.

Your code looks fine for the most part. I don't think you need the .all at the end. The associations will automatically load all that you are referencing under that model.

Though try using the association build method instead:

def duplicate_tasks_to_ticket
  if self.tasks.blank?
    for task in self.category.tasks.all
      self.tasks.build(:name => task.name)
    end
    self.save
  end
end

The build creates a new object of that association, assigning the foreign key for you. Then you just call save on the parent model, and it will do all the proper insert statements.


Actually dexter I had it commented out when i tried it and it's working now. So I guess what I came up with works just fine. Unless someone knows how I can refine it and make it cleaner. It's working now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜