Rails Form for another model

被刻印的时光 ゝ 提交于 2020-01-07 01:26:48

问题


I have a form in pages/contact and want to send the data to another model called ContactForm instead of Pages model, so i guess this is outside the basic convention.. it looks like this:

<%= form_for @contact_form, url: pages_contact_path, :method => :post do |f| %>
...
...
<% end %>

class PagesController < ApplicationController

    def contact
        @contact_form = ContactForm.new(contact_form_params)    
    end
end

I created this route

  post 'pages/contact' => 'pages#contact'

and it all seems to work fine, but no data is recorded. In the local server i can see is processing the POST but is not doing any SQL Transaction.. why??

Started POST "/pages/contact" for ::1 at 2016-06-22 15:58:47 -0300
Processing by PagesController#contact as HTML
Processing by PagesController#contact as HTML
Parameters: {"utf8"=>"✓",     "authenticity_token"=>"WIb3jXmkxP0mxRPSPU0Yj050fFwCQOlm9FatCFiGuSrEaoRNXNtmn/w0ZOMtsZsRUwjq4NQweV+d56T5nFxL5Q==", "contact_form"=>{"name"=>"Diego", "phone"=>"", "email"=>"", "subject"=>"", "message"=>"Hoal"}, "commit"=>"Create Contact form"}

Parameters: {"utf8"=>"✓", "authenticity_token"=>"WIb3jXmkxP0mxRPSPU0Yj050fFwCQOlm9FatCFiGuSrEaoRNXNtmn/w0ZOMtsZsRUwjq4NQweV+d56T5nFxL5Q==", "contact_form"=>{"name"=>"Diego", "phone"=>"", "email"=>"", "subject"=>"", "message"=>"Hoal"}, "commit"=>"Create Contact form"} Rendered pages/contact.html.erb within layouts/application (3.0ms)

Thanks a lot!


回答1:


In the local server i can see is processing the POST but is not doing any SQL Transaction.. why?

No SQL is done as long as no transaction is requested. What your contact_form action does is assigning parameters to a variable, but this variable is not requested to be validated and saved to your database. So it is simply passed over to the view...

What you're intrested of is:

@contact_form = ContactForm.new(contact_form_params)
if @contact_form.save
  # render success
else
  # render errors
end


来源:https://stackoverflow.com/questions/37976319/rails-form-for-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!