Render partial from static page

梦想与她 提交于 2019-12-02 08:43:25

I set up a High Voltage demo application with a form for creating an "Inquiry."

Here is the commit with the changes to make the form work.

Here are the high level steps:

Create a form that will be used in the view:

<%= simple_form_for resource, html: { novalidate: true }, remote: true do |f| %>
  <%= f.input :name %>
  <%= f.input :email %>
  <%= f.input :comments, as: :text %>
  <%= f.button :submit, value: 'Submit' %>
<% end %>

Create a controller to process the request:

class InquiriesController < ApplicationController
  def create
    @inquiry = Inquiry.new(params[:inquiry])
    @inquiry.save
  end
end

The .save method on the Inquiry object will do the magic of emailing the request, or saving to a database, etc. Notice the call to valid? this is provided by ActiveModel::Model and will return true if all the validations pass.

class Inquiry
  include ActiveModel::Model

  attr_accessor :comments, :email, :name

  validates :comments, presence: true
  validates :email, presence: true, email: true
  validates :name, presence: true

  def save
    if valid?
      # send an email or persist to the database...
    end
  end
end

By using .js.erb files we can return a success message, or errors to the static page from the controller endpoint.

<% if @inquiry.valid? %>
  $('#inquiry_form').html('<h2>Thank you for contacting us!</h2>');
<% else %>
  $('#inquiry_form').html('<%= j render 'inquiry_form', resource: @inquiry %>');
<% end %>

What this does is return the "success" message if the request is valid, and returns the form with errors if the request is invalid.

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