简体   繁体   English

Rails - 参数形式值

[英]Rails - params form value

Hello everybody I'm looking for some help with my rails app:大家好,我正在为我的 rails 应用程序寻求帮助:

I don't know why my User isn't created even i have params with value from my simple_form_for, below my controller:我不知道为什么我的用户没有创建,即使我的参数值来自我的 simple_form_for,在我的 controller 下方:

  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

My view looks like this我的观点看起来像这样

    <%= 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 %>

Error is: email can't be blank错误是: email can't be blank

Basically my goal is if current_user create watch with current_user info Else create user with params from simple_form_for then create watch基本上我的目标是如果 current_user 使用 current_user 信息创建手表 否则使用来自 simple_form_for 的参数创建用户然后创建手表

I'm pretty sure that is not the best way to go so feel free to adjust me.我很确定这不是 go 的最佳方式,所以请随时调整我。

Thank in advance for your help预先感谢您的帮助

When you submit a form you can check the parameter structure in rails server log that running on your terminal.当您提交表单时,您可以检查终端上运行的 rails 服务器日志中的参数结构。 It will look like this.它看起来像这样。

{ watch: {
    temp_email: "something@localhost.com"
    ...other details
  }
}

Mind that watch key in params and then sub hash of other params like temp_email and other keys/fields.请注意参数中的watch键,然后是其他参数(如temp_email和其他键/字段)的子 hash。 Here what this might fix your issue.这可能会解决您的问题。 Try to replace following code in your create action.尝试在您的create操作中替换以下代码。

@user = User.create(
          phone: params[:watch][:temp_phone],
          email: params[:watch][:temp_email]
          first_name: params[:watch][:temp_first_name],
          password: "test123456"
        )

Note: This will work only if you really have a something in @watch instance variable.注意:只有在@watch实例变量中确实有某些东西时,这才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM