我参加并删除了我正在使用的方法,如下所示:
def attend
@event = Event.find(params[:id])
if @event.users.include?(current_user)
flash[:error] = "You're already attending this event."
else
current_user.events << @event
flash[:success] = "Attending event!"
end
redirect_to @event
end
def remove_attendee
@event = Event.find(params[:event_id])
@event.users.destroy(params[:user_id])
flash[:success] = "User removed from event."
redirect_to @event
end
然后我还有一个视图,其中列出了参加活动的所有用户:
The attendees of this event are:</br></br>
<% @attendees.each do |user| %>
<li><%= link_to user.name, user %>
<% if @event.users.include?(user) && (user == current_user) %>
<%= button_to 'Remove', remove_attendee_event_path(:event_id => @event.id, :user_id => user.id), :method => :post %>
<% end %>
</li>
<% end %>
最后,我有参加活动按钮:
`<%= button_to 'Attend Event', attend_event_path(@event.id), :method => :post %>`
问题是,当我点击参加,然后删除与会者,它很有效。然后,当我再次尝试参加活动时......它给出了一个错误“在EventsController中出现NoMethodError#参加”
然后,当我只想删除该用户与事件之间的关系时,它会删除我正在使用的当前用户...我做错了什么?
答案 0 :(得分:0)
我认为通常情况下,这看起来像这样:
# config/routes
resources :events do
resources :attendees, :only => [:create, :destroy]
end
# app/controllers/attendees_controller.rb
class AttendeesController < ApplicationController
def create
@event = Event.find(params[:event_id])
if @event.users.include?(current_user)
flash[:error] = "You're already attending this event."
else
current_user.events << @event
flash[:success] = "Attending event!"
end
redirect_to @event
end
def destroy
@event = Event.find(params[:event_id])
@event.users.destroy(current_user)
flash[:success] = "User removed from event."
redirect_to @event
end
end
# app/views/events/show.html.erb
The attendees of this event are:
<% @attendees.each do |user| %>
<li>
<%= link_to user.name, user %>
<% if user == current_user %>
<%= button_to 'Remove', event_attendee_path(:event_id => @event.id, :id => current_user.id), :method => :delete %>
<% end %>
</li>
end %>
答案 1 :(得分:0)
好的,试试这个?
def remove_attendee
user = User.find(params[:user_id])
user_event=user.events.find(params[:event_id])
user.events.delete(user_event)
flash[:success] = "User removed from event."
redirect_to @event
end