我是Rails的新手,我有一个问题,我正在尝试创建项目,但我创建的每个项目都有user_id
nil
。如果我在localhost中创建项目并检查以确保它是在rails控制台中创建的,则会显示user_id = nil
。在此先感谢您的帮助!
使用设计创建用户。
项目控制器
class ItemsController < ApplicationController
def create
@user = User.find(params[:user_id])
@item = Item.new(item_params)
@item.user = current_user
if @item.save
@item = Item.update_items(params[:items])
redirect_to @user, notice: "Item was saved successfully."
else
flash[:error] = "Error creating item. Please try again."
render @user
end
end
private
def item_params
params.require(:item).permit(:name)
end
end
用户控制器
class UsersController < ApplicationController
# before_action :authenticate_user!
def show
@user = User.find(params[:id])
@item = Item.new
@items = @user.items
end
end
答案 0 :(得分:0)
我注释掉了authenticate before_filter,它不允许分配user_id ....愚蠢的错误!
答案 1 :(得分:0)
class ItemsController < ApplicationController
def create
user = current_user
@item = current_user.items.new(params[:items])
if @item.save
redirect_to current_user, notice: "Item was saved successfully."
else
flash[:error] = "Error creating item. Please try again."
render @user
end
end
private
def item_params
params.require(:item).permit(:name)
end
end
确保您的模型中有正确的关联
class Item < ActiveRecord::Base
belongs_to :user
...
end
class User < ActiveRecord::Base
has_many :items
...
end