-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関係について誤解していると思います

エラーを取得するために、レール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

私はこれをRubyonRailsガイドから行うというアイデアを思いつきました

4

3 に答える 3

2

エラーの理由: 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所属する: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 に答える