belongs_to关联不填充user_id

时间:2014-06-10 21:13:25

标签: ruby-on-rails

我有两个模型,想要添加belongs_to关联。用户has_many位置。为此,我做了以下事情:

1)使用rails g migration AddUserToPlace user:references

创建了迁移

这在我的user_id表格中创建了一个places列,其中包含以下迁移:

add_reference :places, :user, index: true

但是,当我创建新地点时,user_id列仍为空白。

我错过了什么?

编辑:

create行动

def create
  @place = Place.new(place_params)

  respond_to do |format|
    if @place.save
      format.html { redirect_to @place, notice: 'Place was successfully created.' }
      format.json { render action: 'show', status: :created, location: @place }
    else
      format.html { render action: 'new' }
      format.json { render json: @place.errors, status: :unprocessable_entity }
    end
  end
end

1 个答案:

答案 0 :(得分:0)

默认情况下不填充user_id。创建新地点时,请务必在参数中包含user_id;

@place = Place.new();
@place.create(name: "jahn", user_id: @current_user.id)

还尝试在user_id

中强制执行PlaceModel
validates :user_id, presence: true

你应该有这样的东西;

def person_params
  params.require(:place).permit(:user_id, :..., :....)
end

`User_id` should be passed from the form. Otherwise for example you could do this;
def create
    @place = Place.new(place_params)
    @place.user_id = current_user.id

    respond_to do |format|
      if @place.save
        format.html { redirect_to @place, notice: 'Place was successfully created.' }
        format.json { render action: 'show', status: :created, location: @place }
      else
        format.html { render action: 'new' }
        format.json { render json: @place.errors, status: :unprocessable_entity }
      end
    end
end