【问题标题】:Rails form doesn't create single params hash with input valueRails 表单不会使用输入值创建单个参数哈希
【发布时间】:2015-01-19 18:08:45
【问题描述】:

我在 Rails 中使用表单时遇到了一点问题。 (我是 Rails 新手)

提交表单后我得到的是这样的:

--- !ruby/hash:ActionController::Parameters
utf8: "✓"
name: Jim
email: Jim@jim.com
subject: hello
message: goodbye
controller: contacts
action: create

应该是这样的:

contact:
    name: Jim
    email: Jim@jim.com
    subject: hello
    message: goodbye

我不知道我在这里做错了什么。这是表单(减去所有引导 div 和 span):

views/contacts/new.html.erb

<%= form_for(@contact, url: contact_path) do |f| %>
    <%= f.text_field :name, name: "name", value: nil, class: 'form-control', placeholder: 'Enter full name' %>
    <%= f.email_field :email, name: "email", class: 'form-control', placeholder: 'Enter email address' %>
    <%= f.text_field :subject, name: "subject", class: 'form-control',
        placeholder: 'Enter subject' %>
    <%= f.text_area :message, name:"message", class: 'form-control', rows: 6, placeholder: 'Enter your message for us here.' %>
    <%= f.submit :submit, class: 'btn btn-default pull-right' %>
<% end %>

config/routes.rb

  get  'contact'   => 'contacts#new'
  post 'contact'   => 'contacts#create'

controllers/contacts_controller.rb

class ContactsController < ApplicationController
  def new 
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact]) #<-- always fails because no :contact
    if @contact.valid?
      if @contact.send_mail
        # todo
      else
        # todo
      end
    else
      flash.now[:error] = params.inspect
      render 'new'
    end
  end
end

models/contact.rb

class Contact 
  include ActiveAttr::Model

  attribute :name
  attribute :email
  attribute :subject
  attribute :message

  validates_presence_of :name
  validates_format_of   :email, with: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  validates_presence_of :subject
  validates_presence_of :message

  def send_mail
    ContactMailer.form_message(self).deliver_now
  end

end

我尝试过使用 form_for(:contact)、使用资源路由、更改模型以使用 mail_form gem,但仍然没有运气。当然,我可以通过执行 params[:name] 等来获取所有值,但它让我感到烦恼的是,它没有创建一个包含所有表单输入值的单个哈希。有谁知道为什么会这样?提前致谢。

【问题讨论】:

  • 我可能是错的,但我认为您通过使用 name: "name" 之类的东西来覆盖 Rails 的默认命名结构。
  • 你是对的!我添加了这些,因为 bootstrapValidator 不会抓取输入进行验证。我删除了它们,调试器显示 :contact 哈希。非常感谢!

标签: ruby-on-rails forms hash params form-for


【解决方案1】:

删除name: '...' 选项,因为助手已经设置了名称,而不是您设置的名称。在您的情况下,rails 将期望字段命名为 contact[name]contact[email],而不是您设置的字段。

【讨论】:

  • 哎呀,我没有看到@japed 发表评论。那就忽略我的回答吧。
猜你喜欢
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多