在rails应用程序中使用创建的对象保存当前用户时,我遇到了问题。
我一直遵循Michael教程,直到第10章(我不需要下面的第11章到第14章的功能)。从这里开始,我为儿童和幼儿园制作了一些支架,并编辑了模型中的关系(例如,用户有很多孩子,孩子属于用户)。其目的是获得一个应用程序,如果用户被分配给家长角色,用户可以创建他或她的一个或多个孩子;或者,如果用户被分配到幼儿园管理员角色,用户可以创建一个幼儿园。之后,应用程序应该帮助分配所有注册儿童到所有注册幼儿园的名额。
我目前的问题是,用户(此时没有角色,只有普通用户)不能在web界面中创建子用户,因为它说在试图保存子用户时“用户必须存在”,因为我认为没有用户被分配给子用户。不幸的是,我不知道如何将当前用户保存到子用户。我发现了一个非常类似的问题,here和我试图跟随答案,但我无法解决问题,相反,我现在得到了一个错误。我将.merge(user: current_user)部件编辑给子控制器,但它给出了错误:
“ActiveModel::ChildrenController#create中的MissingAttributeError不能写入未知属性user_id”
# POST /children.json
def create
@child = Child.new (child_params)
@child.saveuser.rb和child.rb模型:
#app/models/child.rb
class Child < ApplicationRecord
belongs_to :user
validates :user, presence: true
end
#app/models/user.rb
class User < ApplicationRecord
attr_accessor :remember_token, :activation_token, :reset_token
has_many :children, dependent: :destroy
has_many :kindergartens, dependent: :destroy
....
endchildren_controller.rb:
#app/controllers/children_controller.rb
class ChildrenController < ApplicationController
before_action :set_child, only: [:show, :edit, :update, :destroy]
....
def create
@child = Child.new child_params
@child.save
respond_to do |format|
if @child.save
format.html { redirect_to @child, notice: 'Child was successfully created.' }
format.json { render :show, status: :created, location: @child }
else
format.html { render :new }
format.json { render json: @child.errors, status: :unprocessable_entity }
end
end
end
....
def child_params
params.require(:child).permit(:firstname, :lastname, :postalcode, :city, :street, :addr_number, :gender, :disability, :allday, :halal, :koscher, :vegetarian, :vegan).merge(user: current_user)
end
end发布于 2018-02-14 11:30:31
首先,需要将user_id索引添加到childrens表中。
然后
如果您具有登录和注销功能,我的意思是会话当前正在工作,那么您是如何管理用户会话的?像这样吗?
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end如果是,请转到create方法并编辑如下
@child = Child.new child_params
@child.user = current_user
@child.save将这个.merge(user: current_user)从child_params中删除,我希望它能起作用。
如果上面的解决方案不知何故不起作用,那么用表单手动传递user_id,如表单中的那样
<%= f.hidden_field :user_id, value: current_user.id %>然后user_id添加到强参数中,就像其他属性一样。
当user_id正确地通过时,您可以看到测试,那么发生了什么
只是为了测试目的
@child = Child.new child_params
@child.user = User.last
@child.save第2部分
如果您需要像用户有父级那样授予children_controller权限,那么他/她就可以访问children_controller表单,然后创建如下方法
before_action :require_parants, only: [:new, :create] # top of the controller
private
# parant column on the users table is boolean true/false
def require_parants
if !logged_in? || (logged_in? and !current_user.parant?)
flash[:danger] = "Only parants can create child"
redirect_to root_url
end
end基于此的logged_in?
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end然后,当用户不是父用户时重定向到根URL。
希望它能帮上忙
https://stackoverflow.com/questions/48784871
复制相似问题