我有两个模型,想要添加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
答案 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