我正在尝试为用户创建的事件添加加入/取消加入按钮,类似于用户的关注/取消关注按钮。
我不确定如何在#show
事件中定义@rsvpsEvents#show中的NameError 未定义的局部变量或方法`event'for#<#:0x007f9dfaf9d978>
show.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
user.rb
has_many :rsvps
has_many :events, through: :rsvps, dependent: :destroy
event.rb
belongs_to :user
has_many :rsvps
has_many :users, through: :rsvps, dependent: :destroy
答案 0 :(得分: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.events
和event.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
有点乱,但我希望这个想法很明确。
答案 1 :(得分:0)
您的未定义局部变量或方法错误似乎来自尝试通过rsvp_path将:event_id => event
传递给您的控制器。相反,你应该像这样传递事件对象
<%= link_to "Join Event", rsvps_path(event), :method => :post %>
控制器中的行@event = Event.find(params[:id])
将负责确定您传递给它的事件。