2014-02-12 45 views
2

使用Rails 4,這裏是我的代碼:USER_ID沒有在相關對象登記

# event.rb 
class Event < ActiveRecord::Base 
    belongs_to :user 
    has_many :participants 
    has_many :users, through: :participants 
end 

# user.rb 
class User < ActiveRecord::Base 
    has_many :events 
    has_many :participants 
    has_many :events, through: :participants 
end 

# events_controller.rb 
class EventsController < ApplicationController 
    def new 
    @event = Event.new 
    end 

    def create 
    @event = current_user.events.new(event_params) 
    if @event.save 
     flash[:notice] = "Created event successfully." 
     redirect_to event_path(@event) 
    else 
     render :action => 'new' 
    end 
    end 
end 

當我創建一個事件,在@eventuser_idnil。我不知道爲什麼user_id未註冊。我可以解決這個問題:

# events_controller.rb 
def create 
    @event = Event.new(event_params) 
    @event.user_id = current_user.id 
    ... 
end 

但想知道爲什麼第一種方法不起作用。

回答

1

使用@event = current_user.events.build(event_params)

+0

不過'nil'。 :( – Victor

相關問題