The "little faster reason" is exactly why I asked, I was going to code a 
version that do the minimal database work but I suddenly thought this problem 
must have been solved already.

I don't know why I didn't find it, thanks, I will look into it. 

-- 
Nicolas Goy
Programmer

On 1 Apr 2014 at 01:15:20, Jeremy Evans ([email protected]) wrote:

On Sunday, March 30, 2014 9:51:06 PM UTC-7, Nicolas Goy wrote:
Given a many_to_many association,

many_to_many :categories

I want to add an accessor for category_ids.

Until now I was using the following code:

def category_ids
  @category_ids || categories_dataset.select_map(:id)
end

def category_ids=(ids)
  @category_ids = ids
  modified!
end

def after_save
  super
  if defined?(@category_ids)
    self.remove_all_categories
    Category.where(:id => @category_ids).each do |c|
      self.add_category(c)
    end
  end
end

I was wondering if there was a better approach.


The association_pks plugin handles this for you, though it doesn't defer the 
handling until after save.  You can use the instance_hooks plugin to do that:

  plugin :association_pks
  plugin :instance_hooks

  many_to_many :categories

  object.after_save{object.category_pks = [1, 2, 3]}

The association_pks plugin is a little faster than the code you used, since for 
items that haven't changed, it doesn't delete them just to reinsert them later.

Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to