问题描述
大家好,我正在寻求有关 Rails 应用的帮助:
我不知道为什么我的用户没有被创建,即使我有来自我的 simple_form_for 值的参数,在我的控制器下面:
def create
if current_user == nil
@user = User.create(
phone: params[:temp_phone],email: params[:temp_email]
first_name: params[:temp_first_name],password: "test123456"
)
if @user.save
@watch = Watch.new(watch_params)
@watch.user = User.last
else
puts "#{@user.errors.messages}"
end
else
@watch = Watch.new(watch_params)
@watch.user = current_user
end
end
我的观点是这样的
<%= simple_form_for @watch do |f| %>
#DoSomething
<% if current_user == nil %>
<%= f.input :temp_first_name,label: "Name" %>
<%= f.input :temp_email,label: "Email" %>
<%= f.input :temp_phone,label: "Phone" %>
<% end %>
<div class="home-top-btn">
<%= f.button :submit,"Estimer votre montre",class: "btn btn-primary btn-lg" %>
</div>
<% end %>
错误是:email can't be blank
基本上我的目标是如果 current_user 使用 current_user 信息创建手表 否则使用 simple_form_for 中的参数创建用户,然后创建 watch
我很确定这不是最好的方法,所以请随时调整我。
预先感谢您的帮助
解决方法
当您提交表单时,您可以在终端上运行的 rails 服务器日志中检查参数结构。 它看起来像这样。
{ watch: {
temp_email: "something@localhost.com"
...other details
}
}
请注意 watch
在参数中的键,然后是其他参数的子哈希,例如 temp_email
和其他键/字段。
这可能会解决您的问题。
尝试在您的 create
操作中替换以下代码。
@user = User.create(
phone: params[:watch][:temp_phone],email: params[:watch][:temp_email]
first_name: params[:watch][:temp_first_name],password: "test123456"
)
注意:只有当您真的在 @watch
实例变量中有东西时,这才有效。