关于视图:Rails的同一页面上有两种用于不同控制器的表单

Two forms for different controllers on same page in rails

更新:

下面的问题源于具有before_filter来验证用户身份。

我在同一页面上有两个表单,两个不同的form_for都有不同的模型。它们如下,并且都在devise / sessions / new视图中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%h2 Sign in
= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f|
  %div
    = f.label :email
    %br/
    = f.email_field :email
  %div
    = f.label :password
    %br/
    = f.password_field :password
  - if devise_mapping.rememberable?
    %div
      = f.check_box :remember_me
      = f.label :remember_me
  %div= f.submit"Sign in"
= render :partial =>"devise/shared/links"

=form_for BetaSignUp.new do |f|
  .field
    = f.label :email,"Your Email:"
    = f.text_field :email
  .actions
    = f.submit 'Submit'

尽管在betasignup表单中输入新电子邮件时,它并没有像在views / beta_sign_ups / new视图中具有相同表单时那样保存到数据库中。为什么是这样?我需要对其中一个控制器或路由做些什么?

beta_sign_ups_controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class BetaSignUpsController < ApplicationController
  def new
    @beta_sign_up = BetaSignUp.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @beta_sign_up }
    end
  end

  def create
    @beta_sign_up = BetaSignUp.new(params[:beta_sign_up])

    respond_to do |format|
      if @beta_sign_up.save
        format.html { redirect_to root_path, notice: 'Thank you for signing up.  You will be notified when we expand the beta group.' }
        format.json { render json: @beta_sign_up, status: :created, location: @beta_sign_up }
      else
        format.html { render action:"new" }
        format.json { render json: @beta_sign_up.errors, status: :unprocessable_entity }
      end
    end
  end
end

betasignups表单的html输出:

1
2
3
4
5
6
7
8
9
<form accept-charset="UTF-8" action="/beta_sign_ups" class="new_beta_sign_up" id="new_beta_sign_up" method="post"><input name="utf8" type="hidden" value="a?""><input name="authenticity_token" type="hidden" value="K4wlzIZ958PdaC91vV4NMu4PLm3TF+yVebN0ll2VuoI=">

<label for="beta_sign_up_email">Your Email:</label>
<input id="beta_sign_up_email" name="beta_sign_up[email]" size="30" type="text">


<input name="commit" type="submit" value="Submit">

</form>

提交到betasignups表单后,服务器的输出将记录为日志:

1
2
3
4
Started POST"/beta_sign_ups" for 127.0.0.1 at 2012-05-10 11:36:17 -0400
  Processing by BetaSignUpsController#create as HTML
  Parameters: {"utf8"=>"a?"","authenticity_token"=>"K4wlzIZ958PdaC91vV4NMu4PLm3TF+yVebN0ll2VuoI=","beta_sign_up"=>{"email"=>"[email protected]"},"commit"=>"Submit"}
Completed   in 35ms


您仍然可以使用before_filter,只需向其传递一些选项,以便它仅在特定操作上激活,或者对您在表单中使用的任何控制器操作使用它来代替skip_before_filter。