使用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
當我創建一個事件,在@event
的user_id
是nil
。我不知道爲什麼user_id
未註冊。我可以解決這個問題:
# events_controller.rb
def create
@event = Event.new(event_params)
@event.user_id = current_user.id
...
end
但想知道爲什麼第一種方法不起作用。
不過'nil'。 :( – Victor