简体   繁体   中英

How to correctly search models with a join table in rails?

I am trying to set up my models and controllers for a user event setup. It's a many-to-many setup for users to sign up for events. I already have the join table ('users_events') created.

So far I have:

Models:

class User < ActiveRecord::Base
    has_and_belongs_to_many :events, join_table: 'users_events'
end

class Event < ActiveRecord::Base
    has_and_belongs_to_many :users, join_table: 'users_events'
end

I want to be able to be able to query for all events a user is signed up for. Where should this query go? In users_controller or events_controller? What would the search/find code look like?

First of all users_events goes against rails convention. Rails infers table names by alphabetical order so the table should be named: events_users

Then you can do things like:

      current_user.events

Or

     event = Event.create!(name: "foo")
     current_user.events << event

And the other way around..this way you also don't need to mention the join table in your model.

I was able to figure it out. As I elaborated in my reply to Nikolai, I also have a one-to-many relationship in that an event belongs_to (was created by) a user, so user.events was giving me the events the user had created, not what they were attending. Here is how I solved it.

class User < ActiveRecord::Base
    has_many :events
    has_and_belongs_to_many :attending_events, class_name: 'Event'
end

class Event < ActiveRecord::Base
    belongs_to :user
    has_and_belongs_to_many :attendees, class_name: 'User'
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM