How to add a relationship between models from a view

I have events and users. On the event display page, I want to have a button that “visits”. I want to take current_user and add an association to the current event, as a result of which the user "visits" the event.

I have a visit event method in a user model as follows:

def attend!(id)
  current_user.events << event.find_by_id(id)
end

in case of # show page I have the following form, but I don’t think I am doing it right:

<%= form_for @event.users.attend(:id) do |f| %>
  <div><%= f.hidden_field :id %>
  <div class="actions"><%= f.submit "Attend Event" %></div>
<% end %>

I'm just not quite sure how I am making an association ... which I have already set up correctly. In the console, I do this and it works:

@user.events << @event

this adds an association to this user and the event that the user is attending the event. This is properly configured and working. What I'm confused about is adding a button on the event viewer page.

thank

+3
2

, SpyrosP, :

:

# in routes.rb
# I assume you have something like this single line below, just add member block with attend
resources :events do
  member do
    post :attend
  end
end

EventsController create:

dev attend
  @event = Event.find(params[:id])
  current_user.events << @event
  redirect_to @event
end

, , :

<%= button_to 'Attend Event', attend_event_path(@event.id), :method => :post %> 
+2

( css):

<%= form_for Event.new do |f| %>
  <%= f.submit "Attend Event" %>
<% end %>

:

,

<%= button_to 'Attend Event', your_path, :id => .., :method => :post %> 

id- @event.

, params [: id], , .

:

_path , :

:controller => 'users', :action => 'attend'

. , - :

def attend
  event = Event.find(params[:id])
  current_user.events << event
end
+2

All Articles