Reputation: 398
Hello guys I'm learning Ruby on Rails and I'm currently doing an Event application where Users create events and can sign up for the events of other people.
Basic stuff, but I realized that when a user created an event he wasn't automatically added to the attended list. It was not a straightforward as I thought.
The basics is I have a many to many relation between User and Event through a table called Goings. It works pretty well and I can get
User.attended_events
Event.atendees
To get the ActiveRecord relation.
When I create an event in the Events controller I build the event as
@user.events.build(description: event[:description], date: date_from_date_select_params(event, :date))
The date_from_date_select is a helper to build the date into a datetime object.
So when I do @user.save, the object is created but I don't know what id it has or anything like that I just know that it's probably the last one created by the user, so the only way I could figure to get the object was using created_at but because my default_scope is (order date: :desc) and date is user given I didn't know what to do
Event.where(user_id: @user.id).map{|event| @user.attended_events<<event if event.atendees.none?}
This code above here worked perfectly. I get the user events and I append it to the events the user attended only if there are no atendees (the event is new).
The problem is I feel I just wrote something of a spaghetti code and feel like there's a more elegant way to solve this out there. i'm looking to learn
Upvotes: 0
Views: 24
Reputation: 7434
The build
method will return the newly initialized record to you, so instead of re-fetching it, you could try adding it to the collection like this
# build a new event and store it in a variable
new_event = @user.events.build(description: event[:description], date: date_from_date_select_params(event, :date))
# save the event record directly
new_event.save
# append the new event to the "attended_events" collection
@user.attended_events << new_event
Upvotes: 1