Rails控制器参数为空,即使我可以在调试输出中看到它们

时间:2012-02-04 06:14:19

标签: ruby-on-rails ruby-on-rails-3

免责声明:铁杆的新手。我正在使用Rails 3.2

无论如何,我正在尝试为Merchants创建一个表单来登录。我有一个MerchantSessionsController尝试根据登录表单输入创建一个新会话:

这就是我的 应用程序/视图/ merchant_sessions / new.html.erb

<%= form_for(:merchant_session, :url => merchant_sessions_path) do |f| %>
  <div class="field">
    <%= f.label :userName %><br />
    <%= f.text_field :userName %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="actions">
    <%= f.submit "Sign in" %>
  </div>
<% end %>

文件app \ controllers \ merchant_sessions_controller.rb包含:

def create
    merchant = Merchant.find_by_userName(params[:userName])

    if merchant && merchant.authenticate(params[:password])
        merchant_session[:merchant_id] = merchant.id
        redirect_to root_url, :notice => "Merchanthas been logged in"
    else
        flash.now[:error] = "Invalid username or password."
        @title  = "Merchant Signin"
        render "new"
    end
end

不幸的是,params [:userName]和params [:password]继续传递为nil,即使在商家登录页面的调试输出上,我看到userName和密码肯定是传入的。

--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
authenticity_token: 8WsOviJyY1kktPq9dDO+OFePdSKf2uGLY3Pnc4bU2tc=
merchant_session: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  userName: asd
  password: ddsad
commit: Sign in
action: create
controller: merchant_sessions

我还尝试访问params [:action]参​​数,该参数运行正常。为什么userName和password参数为nil?我更改了MerchantSessionsController的名称(以前只是SessionsController),但我认为不应该是问题

1 个答案:

答案 0 :(得分:4)

您查找的用户名和密码位置错误,请注意YAML转储的具体结构:

merchant_session: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  userName: asd
  password: ddsad

和你的表格:

<%= form_for(:merchant_session, :url => merchant_sessions_path) do |f| %>

您希望查看params[:merchant_session][:userName]params[:merchant_session][:password],而不是params[:userName]params[:password]

def create
    mparams  = params[:merchant_session]
    merchant = Merchant.find_by_userName(mparams[:userName])

    if merchant && merchant.authenticate(mparams[:password])
        #...