2014-11-21 45 views
1

我在Rails中的表單有點麻煩。 (我是新來的Rails)Rails窗體不會創建帶輸入值的單個參數散列

什麼遞交表格後,我得到的是這樣的:

--- !ruby/hash:ActionController::Parameters 
utf8: "✓" 
name: Jim 
email: [email protected] 
subject: hello 
message: goodbye 
controller: contacts 
action: create 

它應該是這樣的:

contact: 
    name: Jim 
    email: [email protected] 
    subject: hello 
    message: goodbye 

我不知道我在這裏做錯了。這裏的形式爲(減去所有所述自舉的div和跨距):

視圖/聯繫人/ 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 %> 

配置/ routes.rb中

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

控制器/ 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 

型號/ 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]等來獲得所有的值,但是它讓我感到不想用所有表單輸入值創建單個散列。有誰知道爲什麼會發生這種情況?提前致謝。

+0

我可能是錯的,但我認爲你通過使用'name:'name''來覆蓋rails的默認命名結構。 – 2014-11-21 14:53:01

+0

你是對的!我添加了這些,因爲bootstrapValidator不會獲取驗證輸入。我刪除了它們,調試器顯示:contact hash。非常感謝! – Aurens 2014-11-21 14:58:31

回答

0

刪除name: '...'選項,因爲助手已經設置了名稱,並且它不是您正在設置的名稱。在你的情況下,鐵軌將預計這些字段被命名爲contact[name]contact[email]而不是您正在設置的字段。

+0

Whops,我沒有看到@japed評論。然後忽略我的答案。 – rewritten 2014-11-21 15:02:25

+0

雖然感謝:-) – Aurens 2014-11-21 15:06:16