sql - Rails: Fetch model across many associations -
i've tried wrapping mind around how navigate associations want, can't seem figure out. i'm trying posts
given tag
. each post has title , body text, both of represented taggedtext
. each taggedtext can have many unique tags — tagging multiple people/pages in facebook post (uniqueness enforced in model when saving instance).
class tag < activerecord::base has_many :tagged_texts, through: :tag_ranges end class post < activerecord::base has_many :tagged_texts end class taggedtext < activerecord::base # each taggedtext cannot have more 1 of each tag has_many :tags, through: :tag_ranges belongs_to :post end class tagrange < activerecord::base # taggedtext cannot have more 1 of each tag belongs_to :tagged_text belongs_to :tag end
i tried joining tables, error association named 'tag_ranges' not found on post
:
def get_posts_by_tag(tag, page, posts_per_page) post .joins(:tagged_texts) .joins(:tag_ranges) .joins(:tags) .where('tag.id = ?', tag.id) .uniq .limit(posts_per_page) .offset(page - 1) .to_a end
what missing query work — or should restructure models , associations somehow?
as error states, need add together tag_ranges
association post
model. i've added few associations may or may not find useful, , 1 simplify query greatly. not tagrange
class's associations fine is.
class tag < activerecord::base has_many :tag_ranges # need association in order tagged_texts has_many :tagged_texts, through: :tag_ranges has_many :posts, -> { uniq }, through: :tagged_texts # posts given tag end class post < activerecord::base has_many :tagged_texts has_many :tag_ranges, through: :tagged_texts # post has association named 'tagged_ranges' has_many :tags, -> { uniq }, through: :tag_ranges # tags given post has end class taggedtext < activerecord::base has_many :tag_ranges # tag ranges tag text has_many :tags, through: :tag_range belongs_to :post end
and now, query posts tag:
def get_posts_by_tag(tag, page, posts_per_page) tag.posts.limit(posts_per_page).offset(page - 1).to_a end
hopefully helps!
sql ruby-on-rails activerecord
No comments:
Post a Comment