我試圖向用戶創建的事件添加加入/取消加入按鈕,類似於用戶的Follow/Unfollow按鈕。NameError與多對多關聯
我不知道該怎麼定義@rsvps爲事件#顯示
NameError在活動#顯示 未定義的局部變量或方法'事件」的#<#: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
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
嗯,比我想象的要簡單得多。所以我只需要創建一個rsvps的方法供用戶加入或脫離事件?對不起,如果它的一個基本問題有點新的軌道 – pmanning
不可以。你應該已經''更新'方法在'events_controller'。所以你可以在那裏放入一些數據加入/取消加入用戶。我會在一分鐘內更新我的答案。 –
哦,還有一個。我認爲我從第一次不明白正確。事件可以有多個用戶,對嗎?如果是這樣,你會**需要**加入模型,我的答案真的很糟糕。 –