On Thursday, March 6, 2014 12:21:41 PM UTC-8, Lloyd Hughes wrote:
>
> Hi,
>
> I have a project where by I have a many_to_many association between two
> models. The are agent and campaign. Normal usage will have a user create a
> campaign and add agents at the same time via nested JSON, but if the user
> wants to dynamically add more agents then will use the agent model and pass
> in the campaign_id to link to.
>
> The problem I am having is that if the campaign exists and is already
> assigned the agent and I call self.add_campaign(campaign_obj) it will add a
> duplicate entry to the DB. Thus my join table will have 2 identical entries
> in it (this is not good).
>
> So I fixed this by first querying the agents associated campaigns and then
> if the "new" campaign isn't in that list I add it (This is because if the
> agent is new and hasn't been saved yet, it won't have an id to query for
> associations).The problem with this approach is I have to do it in an
> after_save hook, and the after_save hook doesn't run if I don't actually
> update an actual column in the Agent table.
>
> How can I stop add_campaign from adding a duplicate entry into the join
> table?
> Or how can I force the after_save hook to be run by setting some flag in
> the agent model that specifies the event of a campaign being added as
> changing the DB?
>
You didn't post a code example for what you are doing, so I'm not exactly
sure. It sounds like your are doing something like:
class Agent < Sequel::Model
many_to_many :campaigns
def after_save
self.add_campaign(campaign_obj) # but where does campaign_obj come
from?
end
end
You probably want to do something like:
self.add_campaign(campaign_obj) unless campaign_obj.new? ||
db.from(:agents_campaigns).where(:agent_id=>id,
:campaign_id=>campaign_obj.id).empty?
But it's hard to say for sure without looking at some example code.
BTW, you might want to look into the nested_attributes plugin.
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/groups/opt_out.