开发者

Creating, destroying, then creating a relationship between two models keeps breaking

I have attend and remove_attendee methods I am using shown below:

      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

Then I also have the view in which I list all users attending the event like so:

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 %>

Lastly, I have the attend event button:

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

The problem is when I click attend, then remove attendee, it works great. Then, when I try to attend the event again...it gives me an error "NoMethodError in EventsController#attend"

Then it deletes the current user I am using out of the database when I just want it to de开发者_如何学JAVAlete the relationship between that user and the event...What am I doing wrong?


I think conventionally, this would look something like this:

# 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 %>


Ok, try this?

  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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜