many to many query for ActiveRecord
- by JP
I have three data models, Users, Conversations and Lines, where each conversation has many lines and certain participating users, each line has one conversation and one user and each user has many conversations and many lines.
I have arranged these in ActiveRecord like this:
class Line < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
end
class User < ActiveRecord::Base
has_and_belongs_to_many :conversations
has_many :lines
end
class Conversation < ActiveRecord::Base
has_many :lines
has_and_belongs_to_many :users
end
If I want to create a new conversation with 4 users, where the users are either found or created inside the users table, how would I go about doing this?
I thought I could do:
c = Conversation.new
c.users.find_or_create_by_username('myUsername')
c.save
But this will create a new username in the Users table even if that username already exists! (ie. running the above code 3 times will result in Users having 3 rows with 'myUsername' as the username, one for each conversation, rather than three conversations all with the same 'myUsername' entry listed in their associated users)
I'm not sure how to search for this kind of information with google - can anyone help?