class Post < ActiveRecord::Base
has_many :categorizations
has_many :categories, through: :categorizations
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :post
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :posts, through: :categorizations
end
Für die oben genannte Zuordnung muss ich folgende Abfrage durchführen.Schienen finden alle Datensätze für eine Sammlung von Datensätzen
@posts = Post.includes(:categories).where(active: true)
@categories = @posts.categories
Offensichtlich ist diese Abfrage @categories = @posts.categories
nicht funktioniert, aber wie würde ich das tun?
aktualisieren: Mit beiden Antworten unten ich diesen Fehler
Category Load (1.9ms) SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
SQLite3::SQLException: no such column: categories.post: SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: categories.post: SELECT "categories".* FROM "categories" WHERE "categories"."post" IN (SELECT "posts"."id" FROM "posts")
du kannst das nicht tun, denn wenn du @kategorien haben willst, muss deine Codezeile von 'Category.someting' beginnen. Jetzt, da Sie eine Korrekturbeziehung haben, können Sie '@categories = Category.joins (: posts) .where (posts: {active: true})' – djothefou