开发者

how to add association between models from a view

I have events and users. On the event show page I want to have a button that is "attend." I want to take the current_user and add an association to the current event therefore making the user "attend" the event.

I h开发者_如何学运维ave an attend event method in the user model as follows:

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

in the event#show page I have the following form but I don't think i'm 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 do the association...which I have already setup properly. In the console, I do this and it works:

@user.events << @event

this adds an association to that user and event that the user is attending the event. This is properly setup and works. The thing I'm confused about is how to add a button on the event view page.

Thanks


Instead to add comments to SpyrosP's answer, I'll just write it in my own answer:

You should first create route for attending on event:

# 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

Then in your EventsController create action:

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

And in your view you should create button:

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


It should be like (i leave out css for simplicity) :

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

EDIT :

Since you look to add current user to a particular event, you can just have a

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

with an id parameter of the @event.

When the user posts, your controller actions gets the event id from params[:id], gets the actual event and users your method to associate with the current user.

SECOND EDIT:

Your_path refers to a named route or if you don't use named routes, something like :

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

Now, the attend method is executed when you click the button. Once you do that, you execute something like :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜