复选框选择和表单对象不保存

时间:2012-02-01 21:46:19

标签: ruby-on-rails checkbox

我的表格包含:

  • 两个复选框
  • 用于收集电子邮件地址的文本字段

我不确定这是否是最佳设计,但该模型包含三个属性:

  • email_name(类型字符串)
  • send_once(type boolean)
  • send_anytime(type boolean)

如果填写了两个复选框中的任何一个,我想保存电子邮件地址,否则不保存任何内容。

一切看起来都像我预期的那样,但是一旦我查看了rails控制台,注册模型就是空的。

我的日志文件说明了这个:

Started POST "/pages" for 127.0.0.1 at 2012-02-01 16:34:55 -0500
Processing by PagesController#create as HTML
Parameters: {"utf8"=>"✓",  "authenticity_token"=>"WChW/OmDPS2Td1D3x/36aCJj7V75FdiAPJ9AQvtAIS4=", "post"=>{"email_address"=>"email@examp.le", "send_once"=>"0", "send_any_time"=>"1"}, "commit"=>"Create Signup"}
(0.3ms)  BEGIN
(0.5ms)  SELECT 1 FROM "signups" WHERE "signups"."email_address" = '' LIMIT 1
(0.3ms)  ROLLBACK
Rendered pages/_form.html.erb (3.7ms)

我该如何解决这个问题?目前该模型没有保存。那么,特别是模型和控制器应该是什么样的?

注意:我在Pages控制器内创建一个signup对象(想想:简报)。

控制器

class PagesController < ApplicationController
 def index
  @signup = Signup.new
 end

def create
 @signup = Signup.new(params[:signup])
 respond_to do |format| 
  if @signup.save
    format.html
    #format.js
  else
    format.html {render action: :index}
   end
  end
 end
end

模型

class Signup < ActiveRecord::Base
  attr_accessible :email_address
  # email_regex = come up with something
  validates :email_address, presence: true,
                        #format: {with: email_regex}, uniqueness: {message: 'there can only be one you.'}                                    
end

_ form.html.erb

<%= form_for(@signup, as: :post, url: pages_path) do |f| %>
  <% if @signup.errors.any? %>
    <div id="error_explanation">
    <p><%= pluralize(@signup.errors.count, "error") %> prohibited this post from being saved:</p>
   <ul>
    <% @signup.errors.full_messages.each do |user| %>
    <li><%= user %></li>
    <% end %>
   </ul>
  </div>
 <% end %>

 <div class="field">
   <%= f.label :email_address %><br />
   <%= f.email_field :email_address %>
   <%= f.label :send_once %><br />
   <%= f.check_box :send_once %>
   <%= f.label :send_any_time %><br />
   <%= f.check_box :send_any_time %>

  </div>

  <div class="actions">
   <%= f.submit %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:1)

你的参数被传递为:post和你的create语句正在寻找params [:signup]。您需要更改控制器以查找params [:post]或更改表单以提交给params [:signup]。

<%= form_for(@signup, as: :signup, url: pages_path) do |f| %>

您还需要检查复选框是否已选中 假设您的参数是:

"signup"=>{"email_address"=>"email@examp.le", "send_once"=>"0", "send_any_time"=>"1"}

你想做的事:

class PagesController < ApplicationController
  def index
   @signup = Signup.new
  end

  def create
    @signup = Signup.new(params[:signup])
    if @signup.send_once == "1" or @signup.send_any_time == "1" then
      respond_to do |format| 
        if @signup.save
          format.html
        else
          format.html {render action: :index}
        end
      end
    else
      # what do you want to do if they didn't sign up?  redirect somewhere?
    end
  end
end