2012-09-13 80 views
0

我試圖向用戶創建的事件添加加入/取消加入按鈕,類似於用戶的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 

回答

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 

有點混亂,但我希望這個想法很明確。

+0

嗯,比我想象的要簡單得多。所以我只需要創建一個rsvps的方法供用戶加入或脫離事件?對不起,如果它的一個基本問題有點新的軌道 – pmanning

+0

不可以。你應該已經''更新'方法在'events_controller'。所以你可以在那裏放入一些數據加入/取消加入用戶。我會在一分鐘內更新我的答案。 –

+0

哦,還有一個。我認爲我從第一次不明白正確。事件可以有多個用戶,對嗎?如果是這樣,你會**需要**加入模型,我的答案真的很糟糕。 –

0

您的未定義局部變量或方法錯誤似乎來自試圖通過rsvp_path將:event_id => event傳遞到您的控制器。相反,你應該只傳遞事件對象,像這樣

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

@event = Event.find(params[:id])在你的控制器會照顧搞清楚你通過什麼事件給它的。