user_id未在关联对象中注册

时间:2014-02-12 18:05:51

标签: ruby-on-rails

使用Rails 4,这是我的代码:

# 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

创建活动时,user_id中的@eventnil。我不确定为什么user_id没有注册。我可以解决这个问题:

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

但是想知道为什么第一种方法不起作用。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您的关系名称存在冲突:

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

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

此外,这可能对您有用:How to save attributes to a has_many :through join table with no existing records to build from