0

我正在尝试向用户创建的事件添加加入/取消加入按钮,类似于用户的关注/取消关注按钮。

我不确定在事件#show 中如何定义@rsvps

事件中的名称错误#show undefined local variable or method `event' for #<#:0x007f9dfaf9d978>

显示.html.erb

<%= link_to "Join Event", rsvps_path(:event_id => event), :method => :post %>

events_controller.rb

def show
  @event = Event.find(params[:id])
  @user = current_user
  #@rsvp = ???? something here ????
end

rsvps_controller.rb

class RsvpsController < ApplicationController
  before_filter :signed_in_user

  def create
    @rsvp = current_user.rsvps.build(:event_id => params[:event_id])
    if @rsvp.save
      flash[:notice] = "Joined event."
      redirect_to root_url
    else
      flash[:error] = "Unable to join event."
      redirect_to root_url
    end
  end

  def destroy
    @rsvp = current_user.rsvps.find(params[:id])
    @rsvp.destroy
    flash[:notice] = "Unjoin Event."
    redirect_to current_user
  end
end

这里是模型

rsvp.rb

class Rsvp < ActiveRecord::Base
  attr_accessible :event_id, :user_id

  belongs_to :user
  belongs_to :event

end

用户.rb

has_many :rsvps
has_many :events, through: :rsvps, dependent: :destroy

事件.rb

belongs_to :user

has_many :rsvps
has_many :users, through: :rsvps, dependent: :destroy
4

2 回答 2

0

我认为这段代码会更像rails-ish。

# user.rb
has_many :users_events
has_many :events, through: :users_events

# event.rb
has_many :users_events
has_many :users, through: :users_events

# users_event.rb
belongs_to :user
belongs_to :event

ActiveRecord 做其他所有事情。8)

例如user.eventsevent.users方法。

加入和取消加入用户操作可能由events controller. 更新方法可以如下所示

# events_controller.rb
def update
  respond_to do |format|
    @event = Event.find(params[:id])
    @event.users << current_user if params[:action] == 'join'
    @event.users.delete(current_user) if params[:action] == 'unjoin' 
    if @event.update_attributes(params[:event])
      format.html { redirect_to @event, notice: 'Event was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @event.errors, status: :unprocessable_entity }
    end
  end
end

有点混乱,但我希望这个想法很清楚。

于 2012-09-13T00:47:39.087 回答
0

您未定义的局部变量或方法错误似乎来自试图:event_id => event通过 rsvp_path 传递给您的控制器。相反,您应该像这样传递事件对象

<%= link_to "Join Event", rsvps_path(event), :method => :post %>

控制器中的行将@event = Event.find(params[:id])负责确定您传递给它的事件。

于 2012-09-13T00:58:16.307 回答