Reputation: 231
I have a User and a Event model
When the user is on an event page, I would like that he could click a button to say 'Count me in'. Then I could have the list of all participants in that even.
What kind of form I am supposed to write? Do I need another table between ?
<%= form_tag concert_path(@concert) do %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= submit_tag "count me in", class: "btn btn-primary
<% end %>
I added the suggested code, but I am facing a no routes matches POST register
So I added method: :put
<%= form_tag register_concert_path(@concert), method: :put do %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= submit_tag "count me in", class: "btn btn-primary" %>
<% end %>
Now I can add myself to a concert, but something wierd happens, it tries tp downlad a file register
and says Failed - can't find file
Also How I am supposed to remove the user from the concert? Shall i go for a method unsubscribe and remove the current user from the list?
def unsubscribe
concert = Concert.find(params[:id])
user = User.find(params[:user_id])
concert.users.delete(user)
end
Upvotes: 2
Views: 36
Reputation: 1451
What you are looking for is: has_and_belongs_to_many You need to define the link between concerts and users.
class Concert
has_and_belongs_to_many :users
end
class User
has_and_belongs_to_many :concerts
end
Then in the controller, please use other action(register), you have to add the user to current concert.
def register
concert = Concert.find(params[id])
user = User.find(params[user_id])
concert.users << user # adding the user
concert.save
end
see the association reference
routes.rb
resources :concerts do
member do
put 'register'
end
end
and the view
<%= form_tag register_concert_path(@concert) do %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= submit_tag "count me in", class: "btn btn-primary
<% end %>
Upvotes: 2