I have the following issue: how to manage a many-to-many association between user and command.
I have the following models:
class User < ActiveRecord::Base
has_many :users_commands, dependent: :destroy
has_many :commands, :through => :users_commands
end
class Command < ActiveRecord::Base
has_many :users_commands, dependent: :destroy
has_many :users, :through => :users_commands
end
class UsersCommands < ActiveRecord::Base
belongs_to :users
belongs_to :commands
end
Now if i have:
@user = User.find_by(id: 1)
@command = Command.find_by(id: 3)
1) How can I save their id on the users_commands table?
2) How can I retrieve all the command with user_id =1 later?
I tried with @user.commands.push(@command)
but I have an error message:
NameError: uninitialized constant User::UsersCommand
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/inheritance.rb:125:in `compute_type'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/reflection.rb:178:in `klass'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/reflection.rb:420:in `block in source_reflection'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/reflection.rb:420:in `collect'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/reflection.rb:420:in `source_reflection'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/reflection.rb:557:in `check_validity!'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/associations/association.rb:25:in `initialize'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/associations/has_many_through_association.rb:9:in `initialize'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/associations.rb:157:in `new'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/associations.rb:157:in `association'
from /var/lib/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/associations/builder/association.rb:70:in `commands'
from (irb):9
from /var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'