Controller
def subscribe
#mailchimp_list_id = "01d4743206"
#gb = Gibbon::API.new
#email = params[:email]
#gb.lists.subscribe({
:id => #mailchimp_list_id,
:email => #email,
:double_optin => false,
:send_welcome => false
})
redirect_to root_path, notice: "Whats up"
end
View
<%= form_tag('/posts/subscribe', method: "post", id: "subscribe", remote: "true") do%>
<div class="large-18 columns text-right mailer">
<%= email_field(:email, :email, {id: "mailersub", placeholder: "Enter your email"}) %>
</div>
<div class="large-6 columns text-right mailer">
<%= submit_tag("Submit", id: "mailersubmit") %>
</div>
<% end %>
All I really want to happen is for the mailchimp process to be completed and then then it re-directs to a path with a notice. The controller and view is for a mailer list form, upon submit I would like this to occur.
Any assistance would be greatly appreciated, thanks!
remote: true do ajax request, it can not redirect. u have to remove remote: true OR at js .on ajax:success do location.url = '/'
Here is your answer, you have to render js inside the controller and inline javascript can be used to redirection:
def subscribe
#mailchimp_list_id = "01d4743206"
#gb = Gibbon::API.new
#email = params[:email]
#gb.lists.subscribe({
:id => #mailchimp_list_id,
:email => #email,
:double_optin => false,
:send_welcome => false
})
flash[:notice] = "Whats up"
respond_to do |format|
format.js { render :js => "/" }
end
end
Related
I have contact us form and im working in the development env with localhost, user fills name, email, and message and clicks on send message button and then i receive an email.
I implemented the solution using
Ruby v 2.4.1
Rails v 5.1.4
mail_form
I followed the steps on the below link
https://gist.github.com/stevecondylios/e819a296167a31578d82fac881963789
Before this functionality was working for some email and now does not work at all, I dont get an error and no log shows in the email provider which is mailgun
here is the last logs that i get
Processing by HomepageController#create as JS
Parameters: {"utf8"=>"✓", "homepage"=>{"name"=>"AMER Y BEARAT", "email"=>"bearatamer#gmail.com", "message"=>"klkllkklk", "nickname"=>""}, "commit"=>"Send Message"}
--->>> 1 create contact
--->>> 2 create contact
Test: {
"name": "AMER Y BEARAT",
"email": "bearatamer#gmail.com",
"message": "klkllkklk",
"nickname": ""
}
--->>> 3 create contact
--->>> 4 create contact
Started POST "/homepage" for ::1 at 2021-03-07 11:42:32 -0700
Processing by HomepageController#create as JS
Parameters: {"utf8"=>"✓", "homepage"=>{"name"=>"AMER Y BEARAT", "email"=>"bearatamer#gmail.com", "message"=>"klkllkklk", "nickname"=>""}, "commit"=>"Send Message"}
--->>> 1 create contact
--->>> 2 create contact
Test: {
"name": "AMER Y BEARAT",
"email": "bearatamer#gmail.com",
"message": "klkllkklk",
"nickname": ""
}
--->>> 3 create contact
--->>> 4 create contact
\logs are coming from this controller homepage_controller.rb file
app/controllers/homepage_controller.rb
class HomepageController < ApplicationController
def index
#contact = Homepage.new(params[:homepage])
end
def create
puts "--->>> 1 create contact"
#contact = Homepage.new(params[:homepage])
puts "--->>> 2 create contact"
puts "Test: " + JSON.pretty_generate(JSON.parse(#contact.to_json))
#contact.request = request
puts "--->>> 3 create contact"
respond_to do |format|
puts "--->>> 4 create contact"
if #contact.deliver
puts "--->>> Pass create contact"
# re-initialize Home object for cleared form
#contact = Homepage.new
format.html { render 'index'}
format.js { flash.now[:success] = #message = "Thank you for your message. I'll get back to you soon!" }
else
puts "--->>> Fails create contact"
format.html { render 'index' }
format.js { flash.now[:error] = #message = "Message did not send." }
end
end
end
end
this is partial view
app/views/homepage/_contact_form.html.erb
<%= form_for #contact, url: homepage_index_path, remote: true do |f| %>
<div class="contact-form-container">
<div>
<%= f.label :name %></br>
<%= f.text_field :name, required: true, class: "contact-form-text-area" %>
</div>
<div>
<%= f.label :email %></br>
<%= f.text_field :email, required: true, class: "contact-form-text-area" %>
</div>
<div>
<%= f.label :message %></br>
<%= f.text_area :message, rows: 8, cols: 40, required: true, class: "contact-form-text-area",
placeholder: "Send us a message"%>
</div>
<div class= "hidden">
<%= f.label :nickname %>
<%= f.text_field :nickname, :hint => 'Leave this field blank!' %>
</div>
<div class="btn-send-message">
<%= f.submit 'Send Message', class: 'btn btn-send-message-primary' , remote: true %>
</div>
</div>
<% end %>
<div class="col-md-6" id="flash-message">
<%= render 'flash' %>
</div>
this is create.js.erb file
app/views/homepage/create.js.erb
// Test for ajax success
console.log("This is the create.js.erb file");
// Render flash message
$('#contact').html("<%= j render 'contact_form' %>");
$('#flash-message').html("<%= j render 'flash' %>").delay(3000).fadeOut(4000);
here is development.rb file
config/environments/development.rb
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.default :charset => "utf-8"
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mailgun.org',
port: 587,
domain: '********.com',
enable_starttls_auto: true,
authentication: 'plain',
user_name: 'postmaster#********.com',
password: '***************************'
}
config.action_mailer.raise_delivery_errors = true
Note: other emails in the app works fine, so i dont think it's mailgun configuration issue
I am implementing a messaging solution for my rails app, I keep get the following error.
PG::InvalidTextRepresentation - ERROR: invalid input syntax for integer: ""
LINE 1: ...rsations" WHERE ((sender_id = 3 AND receiver_id = '') OR (se...
class MessagesController < ApplicationController
def create
if current_user.id == message_params[:receiver_id]
redirect_to request.referrer, alert: "You cannot send a message to yourself"
end
conversation = Conversation.where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)",
current_user.id, message_params[:receiver_id],
message_params[:receiver_id], current_user.id
).first
if !conversation.present?
conversation = Conversation.create(sender_id: current_user.id, receiver_id: message_params[:receiver_id])
end
#message = Message.new(user_id: current_user.id,
conversation_id: conversation.id,
content: message_params[:content]
)
if #message.save
format.html { redirect_to request.referrer, notice: 'Message was successfully sent.' }
else
format.json { render json: request.referrer.errors, status: :unprocessable_entity }
end
end
Conversation model.
class Conversation < ApplicationRecord
belongs_to :sender, class_name: "User"
belongs_to :receiver, class_name: "User"
def last_message
message = Message.where(conversation_id: self.id).last
if message.present?
return message
else
return Message.new updated_at: Time.now
end
end
end
That happens because the value you're passing for reciever_id is an empty string, but the data type of that column in your database is an integer.
You can use or to make the query, but it'll transform your empty string to nil:
reciever_id = message_params[:reciever_id]
Conversation.where(sender_id: current_user.id, reciever_id: reciever_id)
.or(Conversation.where(sender_id: reciever_id, reciever_id: current_user.id))
Anyway, you might want to check what you're receiving in order to do the query you're performing. It can be assigning default values, returning early, adding constraints to your routes, etc.
Pasting the form directly works but putting it on the partial does not, i.e below this works.
- if current_user.id != profile.user.id
%small
%button.btn.btn-outline-light{"data-target" => "#modal_large", "data-toggle" => "modal", :type => "button"}
Send Message
= simple_form_for Message.new do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
.row
.col
= f.hidden_field :receiver_id, value: profile.user.id
= f.input :body, autofocus: true, label: "Type Your Message Below"
.form-actions
.row
.col
= f.button :submit, "Send Message", class: "btn btn-primary btn-lg mt-2 float-right"
= render partial: "message", locals: { user: profile.user }
This does not work..
#modal_large.modal.fade{"aria-hidden" => "true", "aria-labelledby" => "modal_large", :role => "dialog", :tabindex => "-1"}
.modal-dialog.modal-lg{:role => "document"}
.modal-content
.modal-header
%h5.modal-title Send a New Message
%button.close{"aria-label" => "Close", "data-dismiss" => "modal", :type => "button"}
%i.ti-close.font-size-14
.modal-body.py-4
= simple_form_for Message.new do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
.row
.col
= f.hidden_field :receiver_id, value: user.id #profile.user.id
= f.input :body, autofocus: true, label: "Type Your Message Below"
.form-actions
.row
.col
= f.button :submit, "Send Message", class: "btn btn-primary btn-lg mt-2 float-right"
The specific problem is on this line below.
= render partial: "message", locals: { user: profile.user }
I've looked all over and can't find a solution that works.
Relevant Controller (profits_controller.rb):
def new_tabs
#market = Market.order('mjsnumber').all.first
#profit = Profit.new
profit_types_markets_products
end
def fetch_market
#market = Market.where(:id => params[:market_id]).first
form = params["form"]
respond_to do |format|
format.js { render layout: false}
end
end
Relevant View (new_tabs.html.erb):
<%= simple_form_for #profit, :remote => true do |form| %>
<% #markets.each_with_index do |market, i| %>
<%= link_to market.nick, fetch_market_path(:market_id => market.id, :form => form, profit: #profit), :remote=>'true', :id => 'navBtn' + market.id.to_s, :class => 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<% end %>
<%= render :partial => 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } %>
Relevant Partial (_edit_partial_form.html.erb):
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
<%= figures_form.input "[test]" %>
<% end %>
Relevant JS (fetch_market.erb):
$("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Routes:
get "/fetch_market" => 'profits#fetch_market', as: 'fetch_market'
It renders the partial fine, and the links appear to contain the FormBuilder information. When I click the link and add a "puts params" to the controller, it shows the params there. But then gives me an error when loading the partial in console:
ActionView::Template::Error (undefined local variable or method `form' for #<#<Class:0x00007fdbd6453648>:0x00007fdbd68db5f8>
Did you mean? fork):
1: $("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: #market, form: form, profit: #profit } ) %>");
Thanks in advance.
In fetch_market method you should to edit form = params["form"] to #form = params["form"]. You was declared local var this is why your code doesnt work. And the name of the file should be fetch_market.js.erb)
I'm new here so I hope it's appropriate for new accounts to ask questions straight away. I've been working with Rails for sometime now and usually I'm pretty good at researching and solving my own problems - but this one has had me stumped for a few days now.
I have a create action being called in a controller that contains an if-else statement that is conditional based on a check_box post parameter. I can see that the parameter is being posted to the controller so the statement should be able to correctly branch but something strange is happening. The controller executes both branches of the statement, but because my parameters are trimmed depending on that check_box, the second branch always errors out. I'm fairly confident this has little to do with routes.
Please see my code below:
Controller:
def create
#quote = Quote.find(params[:quote_id])
if params[:quote_item][:custom] == 1
#quote_item = #quote.quote_items.new(quote_item_params)
#quote_item.rate = nil
#quote_item.custom = true
#quote_item.unit_price = params[:quote_item][:unit_price]
#quote_item.rate_name = params[:quote_item][:title]
else
#quote_item = #quote.quote_items.new(quote_item_params)
#quote_item.custom = false
#rate = Rate.find(params[:quote_item][:rate_id])
#quote_item.unit_price = #rate.price
#quote_item.rate_name = #rate.product.name
end
respond_to do |format|
if #quote.save
format.html { redirect_to #quote, notice: 'Quote item was successfully added.' }
format.json { render :show, status: :created, location: #quote }
else
format.html { redirect_to #quote }
format.json { render json: #quote.errors, status: :unprocessable_entity }
end
end
View:
<% if #rates.any? %>
<%= bootstrap_form_for([#quote, #quote_item], layout: :inline) do |f| %>
<%= f.text_field :title, class: 'input-sm', hide_label: true, :placeholder => "Line Title" %>
<%= f.select(:rate_id, #rates.collect {|r| [r.select_summary_text, r.id ] }, { hide_label: true }, { :class => 'input-sm' }) %>
<%= f.number_field :quantity, class: 'input-sm', hide_label: true, :min => 1, :length => 2, :value => 1 %>
<%= f.text_field :unit_price, class: 'input-sm', hide_label: true, :min => 1, :length => 2, :prepend => "$" %>
<%= f.text_field :note, class: 'input-sm', hide_label: true, :placeholder => "Note (Optional)" %>
<%= f.submit "Add Quote Item", class: 'btn btn-sm btn-default' %>
<%= f.check_box :custom, label: "Override" %>
<% end %>
<% else %>
<div class="well well-sm"><i class="fa fa-usd"></i> No pricing for this customer has been set. Set product pricing for this jobs customer <%= link_to user_path(#quote.job.user) do %>here.<% end %></div>
<% end %>
My create method errors out here:
#rate = Rate.find(params[:quote_item][:rate_id])
With:
ActiveRecord::RecordNotFound (Couldn't find Rate with 'id'=):
app/controllers/quote_items_controller.rb:19:in `create'
This error is correct though, because the rate ID isn't processed in first branch of the if-else statement. I've tried different check_box form fields, directly overriding 'custom' and both branches still run.
Any help here is greatly appreciated!
The params hash contains strings.
Try swapping:
if params[:quote_item][:custom] == '1'
for your original:
if params[:quote_item][:custom] == 1
I am trying to get ajax image uploading working in my rails app. I am using Paperclip for the normal image uploading, and that works fine, but I can't seem to get the ajax method hooked up. I am using the Rack RawUpload and the
File Uploader plugin. I followed the general instructions here, but I am stuck at the actually attaching the image to the new object on create. Here is my Controller code:
#bottle = Bottle.new(params[:bottle])
#bottle.user_id = current_user.id
#file = params[:qqfile].is_a?(ActionDispatch::Http::UploadedFile) ? params[:qqfile] : params[:file]
is_qq = params.has_key?(:qqfile)
if is_qq
params[:bottle][:image] = params.delete(:file)
render :json => { "success" => true }
else
respond_to do |format|
if #bottle.save
format.html { redirect_to '/bottles', notice: 'Bottle was successfully created.' }
format.json { render json: #bottle, status: :created, location: #bottle }
else
format.html { render action: "new" }
format.json { render json: #bottle.errors, status: :unprocessable_entity }
end
end
end
and Here is the view code:
<%= simple_form_for(#bottle, :html => { :multipart => true }) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :brand, :placeholder => 'Brand', :label => false %>
<%= f.input :region, :placeholder => 'Region', :label => false %>
<%= f.input :age, :collection => 5..35, :prompt => "Bottle Age", :label => false %>
<%= f.input :price, :placeholder => 'Price', :label => false, :as => :currency, :input_html => { :class => 'span2' } %>
<%= f.input :image_id, :as => :hidden %>
<%= f.text_area :notes, :placeholder => 'Tasting notes...', :size => "160x5" %>
</div>
</div>
<div class="span3 offset2">
Drag a file from your desktop here...
<div class="well" height="105" style="width:200px;height:300px;">
<!-- <img src="http://placehold.it/200x300" alt="" class="temp_image"> -->
<div id="file-uploader"></div>
</div>
or...
<%= f.file_field :image %>
</div>
<div class="span8 offset2">
<%= f.button :submit, :class => 'btn-primary' %>
<%= link_to bottles_path, :class => 'btn btn-danger' do %>
Cancel
<% end %>
</div>
<% end %>
I am uploading with the File Uploader like this:
var uploader = new qq.FileUploader({
debug: false,
/* Do not use the jQuery selector here */
element: document.getElementById("file-uploader"),
action: '/bottles',
allowedExtensions: ["jpg", "png"],
/*
* This uploads via browser memory. 1 MB example.
*/
sizeLimit: 1048576,
/* Set Article category on submit */
onSubmit: function(id, fileName) {
uploader.setParams({
authenticity_token: $("input[name='authenticity_token']").attr("value")
});
},
onComplete: function(id, fileName, responseJSON){
url = responseJSON.image.image.url;
$('.well').html('<img src="'+url+'" />');
$('input#bottle_image_id').val(responseJSON.image.id);
}
});
It seems to upload using Rack fine and it passes the :file param to the method, but I can't assign param[:bottle][:image] with the param[:file], i get error:
undefined method `[]=' for nil:NilClass
Any help would be greatly appreciated.
EDIT:
So I am able to get the ajax upload to hook into the paperclip upload and add the appropriate parameters, but now I need to update that same object when I submit the rest of the form, not create a new object. How can I store the object created by the ajax upload that contains all the image content and update it once the full form is submitted?
EDIT 2:
The error i get when saving is
undefined method `save' for #<ActiveSupport::HashWithIndifferentAccess:0x007ff961d08e48>
Which I assume is because I am taking the form data and trying to put it in the same #bottle object and the hashes are not matching up.
I patch lib/rack/request.rb at 217 line to solve this problem
replace
{}
with
#env["rack.request.form_hash"] || {}