在Rails 3.2.15中,我正在尝试建立一个名为TopicInterest的has-many-through模型,将Users与Topics关联,将另一个属性保存在TopicInterest中,名为interest_type。在(我认为)通过对TopicInterest的create()调用成功建立连接之后,我无法通过控制台中的TopicInterest获取主题或用户:
irb(main):008:0> newjoin = TopicInterest.create(topic_id: mongo.id, user_id: me.id)
(0.4ms) BEGIN
SQL (0.6ms) INSERT INTO "topic_interests" ("created_at", "interest_type", "topic_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Fri, 01 Aug 2014 16:10:00 UTC +00:00], ["interest_type", nil], ["topic_id", 1], ["updated_at", Fri, 01 Aug 2014 16:10:00 UTC +00:00], ["user_id", 1]]
(6.4ms) COMMIT
=> #<TopicInterest id: 2, user_id: 1, topic_id: 1, interest_type: nil, created_at: "2014-08-01 16:10:00", updated_at: "2014-08-01 16:10:00">
irb(main):009:0> newjoin.save
(0.3ms) BEGIN
(0.3ms) COMMIT
=> true
irb(main):010:0> newjoin.topic
NoMethodError: undefined method `topic' for #<TopicInterest:0x007fae2a06cc70>
from /Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activemodel-3.2.15/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/attribute_methods.rb:149:in `method_missing'
from (irb):10
from /Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/railties-3.2.15/lib/rails/commands/console.rb:47:in `start'
from /Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/railties-3.2.15/lib/rails/commands/console.rb:8:in `start'
from /Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/railties-3.2.15/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :remember_me
has_many :topics, through: :topic_interests
end
主题模型:
class Topic < ActiveRecord::Base
attr_accessible :name, :description
has_many :users, through: :topic_interests
end
TopicInterest模型:
class TopicInterest < ActiveRecord::Base
attr_accessible :interest_type, :user_id, :topic_id
end
我做错了什么?非常感谢您的帮助。
答案 0 :(得分:1)
您需要在belongs_to
模型中添加topic_interest.rb
个引用
class TopicInterest < ActiveRecord::Base
attr_accessible :interest_type, :user_id, :topic_id
belongs_to :topic
belongs_to :user
end
修改强>
由于 Duncan Malashock 检测到此模型中缺少另一个直接关联,我在此处添加以供正确参考。
user.rb
和topic.rb
模型也应与topic_interests
直接关联。
需要在两个提到的模型中添加has_many :topic_interests
。