Вопрос

I feel like what I am doing is very, VERY simple, and all of the resources I've found are more complicated and attempting to replicate them or simplify them leaves me confused.

I have two objects (Stories and Characters) with a HABTM relationship.

My goal is to be able to list all Stories that involve a particular character.

If I do Story.where("stories_characters.character_id = 17"), I get an error that it can't find a column called "stories_characters.character_id" in my story table.

What is the correct way to go about this?

I understand that there is join table weirdness, but every example I saw was filtering on BOTH ids, and not just one...

Это было полезно?

Решение

Do you have a join table? You must have a join table named characters_stories with columns named character.id and story.id. I believe that is a requirement for HABTM. In your models, you need to define:

Story

:has_and_belongs_to_many => :characters

Character

:has_and_belongs_to_many => :stories

Once you have it all wired up, you should be able to just do:

char = Character.find(17)
char.stories
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top