我遇到以下問題:如何管理用戶和命令之間的多對多關聯。 我有以下型號:管理Rails中的多對多關聯
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
現在,如果我有:
@user = User.find_by(id: 1)
@command = Command.find_by(id: 3)
1)我怎樣才能挽救他們的ID在users_commands表?
2)如何在稍後檢索user_id = 1的所有命令?
我試着用@user.commands.push(@command)
但我有一個錯誤信息:
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>'
爲節省協會,嘗試@ user.commands.push(@命令)或@ command.users.push(@user)。這將自動創建聯接模型。對於檢索,我假設你已經嘗試@ user.commands和@ command.users?這些方法應該假設您的數據庫設置正確。 – rdmcfee