Answer the question
In order to leave comments, you need to log in
How to make a "Request a call" form without reloading the page?
Hello.
I'm trying to implement the "Request a call" form. The form is on every page. I do according to the "Model without a table in the database" method. (I did not find another way) I immediately had problems with the fact that I could not bind the form to the model object. I had to do this (I read that it is not recommended to do this)
= form_for Message.new do |f|
...
= form_for @message do |f|
...
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :phone
validates_presence_of :name
validates_format_of :phone, :with => /\A[0-9]{10}\Z/, :allow_blank => true, :allow_nil => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
UserMailer.create_page(@page).deliver
flash[:notice] = "Message sent"
else
render :new
end
end
end
Answer the question
In order to leave comments, you need to log in
1. This form is rendered on every page, so the @message variable must also be set on every page, not just in the Messages controller . That is, if you display this form on the page of posts and a specific post, then in some PostsController in the show and index methods this variable must also be defined.
2. In order for the form not to reload the page, it is enough to pass the remote: true parameter to it . And what to do after the submission, describe in the appropriate JS view (for example, messages/create.js.erb )
= form_for @message, remote: true do |f|
...
I did something similar. I just didn’t use js view, but sent it immediately from the controller.
But couldn't make it work.
something like
@message = Message.new(params[:message])
@company = Company.friendly.find(params[:name])
if @message.valid?
UserMailer.call(@company).deliver
render json: @message, status: :ok
else
render json: @message.errors, status: :unprocessable_entity
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question