0

我遇到了一些我怀疑并不难解决的问题,只是我缺乏经验让它变得很难。

我有我的路线

match '(/:client_id)/signup',   to: 'users#new'

现在,如果客户端向 www.myappurl.com/123/signup 的任何人发送链接,则用户将注册并且他的用户模型将接收 client_id 作为参数(我稍后需要)。

控制器:

def new
  @user = User.new
  if signed_in?
    redirect_to root_path
  end
end

def create
  @user = User.new(params[:user])

  if @user.save
    sign_in @user
    flash[:success] = t("users.new.welcome")
    redirect_to @user
  else
    render 'new' #and this is the problem
  end
end

问题是,当用户提交他的应用程序时,他提供的信息没有通过验证,然后呈现“新”操作,但我失去了这个 :client_id 参数,因此他和客户之间的关联。

我试过redirect_to 并传递参数。这有效,但不显示错误消息。

任何想法如何解决它?

编辑

我在提交无效信息之前的调试:

controller: users
action: new
locale: en
client_id: '2'

之后:

!binary "dXRmOA==": ✓
!binary "YXV0aGVudGljaXR5X3Rva2Vu": ldtdjuWAWHB052qY3ASoH1Mv3XYtrdRcL56DgSaYC0Q=
!binary "dXNlcg==": !ruby/hash:ActiveSupport::HashWithIndifferentAccess
!binary "Zmlyc3RfbmFtZQ==": ''
!binary "bGFzdF9uYW1l": ''
!binary "ZW1haWw=": ''
!binary "Y2xpZW50X2lk": '2'
!binary "cGFzc3dvcmQ=": ''
!binary "cGFzc3dvcmRfY29uZmlybWF0aW9u": ''
!binary "Y29tbWl0": Create my account
action: create
controller: users
locale: en

服务器日志

Started POST "/en/users" for 127.0.0.1 at 2012-10-16 07:10:31 +0800
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ldtdjuWAWHB052qY3ASoXYtrdRcL56DgSaYC0Q=", "user"=>{"first_name"=>"", "last_name"=>"", "email"=>"", "client_id"=>"2", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account", "locale"=>"en"}
(0.4ms) BEGIN
User Exists (2.5ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('') LIMIT 1
(0.1ms)  ROLLBACK
Rendered shared/_error_messages.html.erb (18.6ms)
Rendered users/_fields_for_registration_no_verification.html.erb (36.9ms)
Rendered users/_password_fields.html.erb (3.6ms)
Rendered users/new.html.erb within layouts/application (77.5ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_google_tracking_code (0.0ms)
User Load (2.4ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" IS NULL  LIMIT 1
Rendered layouts/_header.html.erb (8.7ms)
Rendered layouts/_footer.html.erb (1.5ms)
Completed 200 OK in 437ms (Views: 213.4ms | ActiveRecord: 14.9ms)

编辑

我找到了问题的真正根源(与下面的答案不同)。问题是当我在表单中使用隐藏字段时,我使用了以下代码:

<%= f.hidden_field :client_id, { :value => params[:client_id]} %>

事实证明,一旦我删除了该{ :value => params[:client_id]}部分,在注册失败后一切都开始按预期工作。永远感谢您的帮助。

4

1 回答 1

2

这是因为当验证失败并呈现 new 时,您:cliend_id会从@user对象中丢失。

def new
  if params[:client_id]
    @user = User.new(:client_id => params[:client_id])
  else
    @user = User.new
  end 
  if signed_in?
    redirect_to root_path
  end
end

在您users/new.html.haml看来,请确保您拥有:client_id.

=form_for @user do |u|
  =f.hidden_field :client_id  #This will prevent your client_id from getting lost when validation fails.

更简洁的方法是将 before_filter 用于您的新操作。希望你能明白。

于 2012-10-15T12:31:52.750 回答