-1
SELECT "groups".* FROM "groups"
INNER JOIN "groups_interests" ON "groups"."id" = "groups_interests"."group_id"
WHERE "groups_interests"."interest_id" = 1

SQLite3::SQLException: no such column: groups_interests.interest_id: SELECT "groups".* FROM "groups" INNER JOIN "groups_interests" ON "groups"."id" = "groups_interests"."group_id" WHERE "groups_interests"."interest_id" = 1

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: groups_interests.interest_id: SELECT "groups".* FROM "groups" INNER JOIN "groups_interests" ON "groups"."id" = "groups_interests"."group_id" WHERE "groups_interests"."interest_id" = 1

我想我对外键和 has_many 关系有误解

为了得到错误,我使用了 rails c

Interest.find(1).groups

我也希望这个命令正确运行

Groups.find(5).interests

class Group < ActiveRecord::Base
  attr_accessible :description, :name, :project_id
  has_many :students
  has_many :group_interests
  has_many :interests, :through => :group_interests
  belongs_to :project

  validates :name, presence: true, uniqueness: { case_sensitive: false }
end


class Interest < ActiveRecord::Base
  attr_accessible :name

  has_many :group_interests
  has_many :groups, :through => :group_interests

  validates :name, presence: true, uniqueness: { case_sensitive: false }

end

class GroupInterest < ActiveRecord::Base
  attr_accessible :group_id, :interest_id

  belongs_to :groups
  belongs_to :interests

end

我从ruby​​ on rails guides得到了这样做的想法

4

3 回答 3

2

你的错误原因:有两个错别字

class GroupInterest < ActiveRecord::Base
  attr_accessible :group_id, :interest_id

  belongs_to :groups      #should be :group
  belongs_to :interests   #should be :interest

end
  • Grouphas_many :group_interests(复数)
  • GroupInterest属于_to :group (单数)

编辑has_and_belongs_to_many-除非您确定永远不需要关联表中的新属性,否则不要使用。has_many :through灵活得多。

于 2013-02-21T13:51:40.657 回答
1


class GroupInterest < ActiveRecord::Base
  attr_accessible :group_id, :interest_id

  belongs_to :group
  belongs_to :interest

end

Group.find(5).interests
于 2013-02-21T13:48:11.260 回答
1

你为什么不使用has_and_belongs_to_many

class Group < ActiveRecord::Base
  attr_accessible :description, :name, :project_id
  has_many :students
  has_and_belongs_to_many :interests
  belongs_to :project
  validates :name, presence: true, uniqueness: { case_sensitive: false }
end


class Interest < ActiveRecord::Base
  attr_accessible :name  
  has_and_belongs_to_many :groups
  validates :name, presence: true, uniqueness: { case_sensitive: false }
end

class GroupInterest < ActiveRecord::Base
  attr_accessible :group_id, :interest_id    
end

您需要更改您的表结构join_table。请参阅为此提供的链接。

于 2013-02-21T13:49:19.317 回答