0

I'm pretty new in rails so please be patient with my ignorance. I have two models: user and event. I've generated the migration that creates the join table events_users and I've declared has_and_belongs_to_many on both models. What I want to do generally is to create a list of users per event. I have a join method in my events controller that does the following:

def join
if current_user
    @events_users = Events_users.new
    @events_users.user = current_user
    @events_users.event = @event
    @events_users.save
    redirect_to events_url
else
    redirect_to new_user_session_url
end
end

In my routes.rb, I have this:

    match 'events/:id' => 'events#join', :as => :join

Basically, the method doesn't seem to work and my events_users table doesn't update. I need to know what I have to do when a user clicks 'Join' such that his/her id and the event id is added in the events_users table.

4

1 回答 1

0

您可以将其简化为:

def join
  if current_user
    @event.users << current_user
    @event.save

    redirect_to events_url
  else
    redirect_to new_user_session_url
  end
end

此外,添加@event.users可以处理任何数组操作。

于 2012-05-17T09:41:52.343 回答