I am making a search function with rails, but when I try to search for the model with which the association is formed, an error occurs.

Joined with tweets table to search for name in categories table

Tweet.joins (: categories) .where ('categories.name LIKE (?) "% # {Search}%")
Can't join'Tweet' to association named'categories';perhaps you misspelled it?

The above error will occur
When I checked, it seems that the combination is not working well and I have to set it on the model side, but I wrote as follows, but the error is not resolved
What should I do?


tweet table

id text school_a.id school_b.id
1 Good morning 1 2

school_a.id refers to A High School
school_b.id refers to B high school

categories table

id name
1 A high school
2 B high school

Tweet model

belongs_to: school_a, class_name:'Category', foreign_key:'school_a_id'
  belongs_to: school_b, class_name:'Category', foreign_key:'school_b_id'

Category model

has_many: tweets
has_many: school_a_tweets, class_name:'Tweet', foreign_key:'school_a_id'
has_many: school_b_tweets, class_name:'Tweet', foreign_key:'school_b_id'
  • Answer # 1

    That's because Tweet doesn't have a has_many: categories association.

    At first glance, the Category that Tweet model has is has_many, but in reality, school_a.id and school_b.id are recognized as different things.

    If you want to make a model as it is, it seems better to search Category with like and then search for Tweets that have it based on the category of the search result.

Related articles