2013-02-21 89 views
-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關係Ruby on Rails的:SQLite3的::的SQLException:沒有這樣的列:

爲了得到錯誤我用鋼軌Ç

Interest.find(1).groups 

我也想這個命令來運行correcty

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

回答

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你的表結構。請參閱爲此提供的鏈接。

1


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

    belongs_to :group 
    belongs_to :interest 

end 

Group.find(5).interests 
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_many,除非您確定永遠不需要關聯表中的新屬性。 has_many :through更靈活。

相關問題