On Friday, May 31, 2019 at 7:57:59 AM UTC-7, JB wrote:
>
> Hello, I'm new to Sequel, so please excuse my maybe simple question. 
>
> I want to set up a many to many association. When adding such an 
> association, it leads to a UNIQUE constraint violation. It seems like I 
> miss something here. Maybe you could help me, please? I have the following 
> code (simplified):
>
> --------------------------------- tables ---------------------------------
>
> db.create_table? :tickets do
>       primary_key   :id
>       String            :key
>       String            :ticket_type_name
>       String            :priority
> end
>
> db.create_table? :editors do
>       Integer           :employee_number, primary_key: true
>       String            :name
> end
>
> db.create_table?  :tickets_editors do
>       foreign_key   :ticket_id, :tickets
>       foreign_key   :editor_id, :editors
>       primary_key  [:ticket_id, :editor_id]
> end
>
> --------------------------------- models ---------------------------------
> class Ticket < Sequel::Model
>       many_to_many :editors
> end 
>
> class Editor < Sequel::Model
>       many_to_many :tickets
>       unrestrict_primary_key
> end 
>
>
> # I'm retrieving data from an API, create for every ticket a *ticket 
> *instance 
> and also an *editor *variable which is a hash containing the values to add
>
> # [each loop:]
> *ticket*.add_editor(*editor*)
>

When the add_* association method is called with a hash, it always creates 
an object in the associated table.  If you want it to use an existing row 
in the editor table if it exists:

if e = Editor[editor[:employee_number]]
  ticket.add_editor(e)
else
  ticket.add_editor(editor)
end

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 https://groups.google.com/group/sequel-talk.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sequel-talk/c6d402ec-b8c1-4067-9a1a-323ffa6a9a31%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to