Ruby on Rails:SQLite3 :: SQLException:没有这样的列:

时间:2013-02-21 13:43:59

标签: sql ruby-on-rails associations rails-activerecord

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

执行此操作的想法

3 个答案:

答案 0 :(得分:2)

您出错的原因:有两个拼写错误

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

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

end
  • Group has_many :group_interests(复数)
  • GroupInterest belongs_to :group(单数)

编辑 - 除非您确定在关联表中永远不需要新属性,否则请勿使用has_and_belongs_to_manyhas_many :through更加灵活。

答案 1 :(得分:1)



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

  belongs_to :group
  belongs_to :interest

end

Group.find(5).interests

答案 2 :(得分: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上更改表格结构。请参阅为此提供的链接。