I'm new to rails and still learning the associations and I'm stuck with a model relationship.
I have a model that I want associated with two parent models so that when an instance of that model is created it is automatically associated with the two parent models. I'm not sure if this is a polymorphic relationship or not. If it is, can someone show me how to handle the create so that it creates the proper links. I'm not quite getting the polymorphic relationships from the docs.
Currently I'm doing a create with the one model and adding the entry to the other model. I would like to think there is a way to get this to happen automatically but I'm not sure how to do it.
Current Implementation:
entry = @pool.entries.create(new_entry_params)
current_user.entries << entry
current_user.save
I want to set it up this way so I can easily show all entries for a specific user from both an instance of the user and an instance of the pool.
Here is what I have so far for the model / database setup:
Models:
class User < ActiveRecord::Base
has_many :pools, through: :pool_memberships, dependent: :destroy
has_many :entries, dependent: :destroy
end
class Pool < ActiveRecord::Base
has_many :users, through: :pool_memberships, dependent: :destroy
has_many :entries, dependent: :destroy
end
class Entry < ActiveRecord::Base
belongs_to :user
belongs_to :pool
end
Migration table for entry:
class CreateEntries < ActiveRecord::Migration
def change
create_table :entries do |t|
t.references :pool, index: true
t.references :user, index: true
t.string :name
t.integer :pool_id
t.integer :user_id, index: true
t.timestamps
end
end
end
Is this the "Rails" way of doing this? Or am I way off base. Thanks for any help!
First of all, you don't need current_user.save
as you didn't modify current_user object. :)
This should do the trick:
@pool.entries.create(new_entry_params.merge(:user_id => current_user.id))