Any suggestion for contact form rails 4 - ruby-on-rails

I am a newbie in Rails , trying to make a contact form for my app, but I can not catch the parameters that comes from contact form (like name and message) in Emailer class without asscociating a model. Any suggestion on that? Here are the list of classes and controllers.
My Emailer class is :
class Contact < ActionMailer::Base
default from: "from#example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
# en.contact.send_email.subject
def send_email(contact)
#greeting = "Hi"
mail to: "ostadfree#gmail.com"
end
end
Staticpages controller is :
def email_contact()
Contact.send_email().deliver
redirect_to contact_url
end
Contact.html.erb is include a form and two buttons at the end:
<%= submit_tag "Submit", class: "btn btn-large btn-primary" %>
<%= link_to 'Send Email', email_contact_path %>
and send_email.text.erb is :
Contact#send_email
<%= #greeting %>, find me in app/views/app/views/contact/send_email.text.erb
<%#= "Name :" + #name.to_s %>
Thanks.

Based on your code, you really don't have a grasp on how rails is designed to work. You're probably better off following a tutorial than getting a question like this answered here.
http://seanrucker.com/simple-ruby-on-rails-contact-form-using-activemodel-and-pony/

Try this:
in mailer:
def send_email(name,message)
#greeting = "Hi"
#name = name
#message = message
mail to: "ostadfree#gmail.com"
end
in controller:
def email_contact()
Contact.send_email(params[:name],params[:message]).deliver
redirect_to contact_url
end
where name and message - names of form's fields. If it sent a mails before, that code should work.
Anyway, check it, really: http://guides.rubyonrails.org/action_controller_overview.html#parameters

Related

undefined method - issues calling a helper method from a partial in a mail controller

I've set up an ActionMailer to email and pull a partial to post the data for the user, however the helper methods are comming back as undefined - i moved them to the application helper but still the same error, I think its in the way im passing the variable to the mailer ?
I've searched for same issue online but find that theres no concise response - I fear I'm doing something basic somwewhere wrong
Error:
undefined method `tidy_address' for #<#<Class:0x007f5c90681b10>:0x007f5c90ad8ba0>
My partial in order views : _enquiry_details.html.erb
<div class="row">
<div class="col-xs-2">
<h3><%= #customer.name %></h3>
<hr>
<h5><%= tidy_address(#customer.locations.first) %></h5>
<% #phone_number.each do |pn| %>
<h5><%= pn.name %> : <%=pn.phone_number.phone%></h5>
<% end %>
in my user mailer.rb
def lead_received(enquiry)
#order=enquiry
if #order.user
#customer=#order.user
else
#customer=#order.company
end
#locations=#customer.locations
#phone_number=#customer.phone_maps
mail to: "myemailaddress#domain.com", subject: "New Lead Received"
end
which I call with this passing the order , think this is where im going wrong
in order controller..
if #order.save
UserMailer.lead_received(#order).deliver_now
For clarity in my mailer view lead_received.html.erb
<%= render "orders/enquiry_details" %>
And finally in my locations helper
module LocationsHelper
def google_string(lat,long,size)
case size
when "s"
mysize="150x150&zoom=12"
when "m"
mysize="350x300&zoom=14"
when "l"
mysize="570x300&zoom=13&scale=2"
end
"https://maps.googleapis.com/maps/api/staticmap?"+URI.encode("markers=#{lat},#{long}&size=#{mysize}&key=AIzaSyAxRuThoVl-xziFElt3GPCESLsaye4_aGA")
end
# Return a sorted neat adress block
def tidy_address(location)
unless location.blank?
t_address=""
t_address="#{location.address1}<br>" if location.address1.present?
t_address=t_address+location.address2+"<br>" if location.address2.present?
t_address=t_address+location.address3+"<br>" if location.address3.present?
t_address=t_address+location.city+"<br>" if location.city.present?
t_address=t_address+location.postcode if location.postcode.present?
# t_address=t_address+"("+location.id.to_s+")"
#t_address=t_address+"<br><a href=''>Directions to here</a>"
t_address.html_safe
else
t_address="<link_to 'Add an address' '#'>".html_safe
end
end
end
Add the helper in the mailer code to use inside mailer.
class UserMailer < ActionMailer::Base
default from: "" # default from email
helper LocationsHelper
helper UserHelper
def lead_received(enquiry)
#order=enquiry
if #order.user
#customer=#order.user
else
#customer=#order.company
end
#locations=#customer.locations
#phone_number=#customer.phone_maps
mail to: "myemailaddress#domain.com", subject: "New Lead Received"
end
end

Rails 4 - mailer - how to pass arguments to a mailer method

I'm trying to figure out how to setup a mailer class in my Rails 4 app.
I have made a mailer called admin_notes. I want to use it to send emails to the internal team when certain actions are taken across the site.
In my mailer/admin_note.rb, I have:
class AdminNote < ApplicationMailer
def unknown_organisation(organisation_request, user_full_name, name)
#organisation_request =
#user_full_name =
#organisation_request.name =
# #greeting = "Hi"
mail( to: "test#testerongmail.com",from: "test#testerongmail.com", subject: "A new organisation")
end
end
I have an organisation_requests model. It has:
class OrganisationRequest < ActiveRecord::Base
belongs_to :profile
delegate :user_full_name, to: :profile, prefix: false, allow_nil: true
The organisation request table has an attribute called :name in it.
When a new organisation request is created, I want to send an admin note to the internal team, alerting someone to start a process.
I'm struggling to figure out how I define the three variables in the mailer method.
I plan to add the send email call to the create action in the organisation requests controller.
How can I set these variables?
Form to create an organisation request is:
<%= simple_form_for(#organisation_request) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :organisation_id, collection: #all_organisations << ['other', nil] %>
</div>
<div class="form-inputs">
<%= f.input :name %>
</div>
<div class="form-actions">
<%= f.button :submit, "Create", :class => 'formsubmit' %>
</div>
<% end %>
NEW ATTEMPT:
I have a create action in my organisation controller, I added this service class request for an email:
def create
#organisation_request = OrganisationRequest.new(organisation_request_params)
#organisation_request.profile_id = current_user.profile.id
if #organisation_request.save
NewOrgRequestService.send_unknown_organisation_requested_flag(organisation_request)
return redirect_to(profile_path(current_user.profile),
flash[:alert] => 'Your request is being processed.')
else
# Failure scenario below
#all_organisations = Organisation.select(:title, :id).map { |org| [org.title, org.id] }
render :new
end
end
I then have a services/organisations requests/NewOrgRequestService.rb
class OrganisationRequest < ActiveRecord::Base
class NewOrgRequestService
attr_accessor :organisation_request
def self.send_unknown_organisation_requested_flag(organisation_request)
if #organisation_request.name.present?
AdminNote.unknown_organisation_requested(organisation_request, user_full_name, name).deliver_later
end
end
end
end
The AdminNote mailer has:
class AdminNote < ApplicationMailer
layout 'transactional_mailer'
def unknown_organisation_requested(organisation_request, user_full_name, name)
#organisation_request = #organisation_request
#user_full_name = #organisation_request.user_full_name
#name = organisation_request.name
# #greeting = "Hi"
mail
to: "test#testerongmail.com",from: "test#testerongmail.com", subject: "A new organisation"
end
end
This doesnt work, but I'm wondering if Im on the right track? Im not sure if the create action in the controller needs to have some kind of reference to the services/organisation_requests/ path that gets to the file??
I think I may have made a bigger mess than I started with - but I'm out of ideas for things to try next.
This may help you.
In your mailer method
def unknown_organisation(org,user)
#org = org
#user = user
mail(to: "test#testerongmail.com",from: "test#testerongmail.com", subject: "A new organisation")
end
In your controller method after saving organization_request and this is how you set your variable. You can pass variable you want.
AdminNote.unknown_organization(#organization_request, current_user).deliver_now
In your mailer template access passed value as you do in action view. And this is how you use your variable.
<%= #org.name %>
<%= #org.full_name %>
Hope this helps
If you want to queue message or send later you can use ActiveJob to send mails in the background.
For more, see http://guides.rubyonrails.org/active_job_basics.html
I know I am super late but here I go.
I understand that you are trying to send in some parameters (values) to mailer so that you can use it while sending an email.
To do so you just need to define a mailer method that accepts some parameters. What you have done is right in your AdminNote Mailer unknown_organization method.
Let's get to your NEW ATTEMPT.
Everything you have done there seems about right except you are passing an undefined variable organization_request. You have created an instance variable #organization_request but you are passing something that is not defined. Here
NewOrgRequestService.send_unknown_organisation_requested_flag(organisation_request)
That is your first problem. This can be improved as:
Your Organizations#create
def create
#organisation_request = OrganisationRequest.new(organisation_request_params)
#organisation_request.profile_id = current_user.profile.id
if #organisation_request.save
#organisation_request.send_unknown_organisation_requested_flag
redirect_to(profile_path(current_user.profile),
flash[:alert] => 'Your request is being processed.')
else
# Failure scenario below
#all_organisations = Organisation.select(:title, :id).map { |org| [org.title, org.id] }
render :new
end
end
And your model can be as follows:
class OrganisationRequest < ActiveRecord::Base
def send_unknown_organisation_requested_flag
if self.name.present?
AdminNote.unknown_organisation_requested(self).deliver_later
end
end
end
I don't know why you are defining a class inside your model class.
Your Mailer should look like below:
class AdminNote < ApplicationMailer
layout 'transactional_mailer'
def unknown_organisation_requested(organisation_request)
#organisation_request = organisation_request
#user_full_name = #organisation_request.user_full_name
#name = organisation_request.name
# #greeting = "Hi"
mail
to: "test#testerongmail.com",from: "test#testerongmail.com", subject: "A new organisation"
end
end
There are a lot of typos and method implementation errors here.

Action Mailer problems (beginner)

If I'm entirely honest, I don't understand action mailers in their entirety and I'm finding it hard to discover a learning resource that isn't using an app which is of a completely different context (e.g teamtreehouses todo app). I would really appreciate a little help.
I have a business directory, I want each listings show page to have a form which when filled in, sends the entered info to the listings attached email.
Here's my code:
Mailers/Enquiry.rb
class Enquiry < ActionMailer::Base
default from: "admin#uk-franchise.co.uk"
def lead(listing, info)
#listing = listing
mail(to: #enquiry.email, subject: 'Email Testing Rails App')
mail(to: #listing.leadrecepient, subject: "test")
end
end
listings controller method
def lead
info = params[:leadname]
notifier = Notifier.lead(#listing, info)
end
Routes I'm stuck on configuring as I don't fully understand them for mailers.
What I have in the show listing view so far
<%= form_for lead_path(#leadname, #listing), method: :put do |lead| %>
<% end %>
Again, if anyone could provide me with a learning resource that would accommodate this scenario or a little help I would really appreciate it!
Here's what you have to do:
Do not use mail method twice in one method
class Enquiry < ActionMailer::Base
default from: "admin#uk-franchise.co.uk"
def lead(listing)
#listing = listing
mail(to: #listing.leadrecepient, subject: "test")
end
end
Send your email from within controller action:
class ListingsController
def lead
##listing = Listing...
Enquiry.lead(#listing).deliver
end
end
routes.rb:
# ...
resources :listings do
member do
put :lead
end
end
# ...
view:
<%= form_for lead_listing_path(#listing), method: :put do |listing| %>
<% end %>

Ruby on rails can't create with params

I have a from created in Ruby on rails. The code the form looks like this:
<%= simple_form_for(#action) do |f|%>
<%= render 'shared/error_messages' %>
<%=f.label :action_name, "Action name"%>
<%=f.text_field :action_name%></br>
<%=f.input :startDate,:as => :datetime_picker, :label =>"Start date"%>
<%=f.input :endDate,:as => :datetime_picker, :label =>"End date"%>
<%=f.label :contentURL, "Content url"%>
<%=f.text_field :contentURL%></br>
<%= f.button :submit, class: "btn btn-large btn-primary" %>
<%end%>
But when I click the submit button I get this error:
undefined method `permit' for "create":String
def action_params
params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)
All other forms a working ok, I guess it is something really obvious, just can't see it :(
I really appreciate any help, solving this problem.
Thanks!!
EDIT:
Controller code:
def create
action = Action.new(action_params)
if #action.save
flash[:success] = "New Action saved"
redirect_to "/"
else
render 'new'
end
end
private
def action_params
params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)
end
In Rails 4, you must use Strong Parameters in your controllers. Here's some explanation from the official blog. And some example:
class PeopleController < ActionController::Base
# This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
# without an explicit permit step.
def create
Person.create(params[:person])
end
# This will pass with flying colors as long as there's a person key in the parameters, otherwise
# it'll raise a ActionController::MissingParameter exception, which will get caught by
# ActionController::Base and turned into that 400 Bad Request reply.
def update
redirect_to current_account.people.find(params[:id]).tap do |person|
person.update_attributes!(person_params)
end
end
private
# Using a private method to encapsulate the permissible parameters is just a good pattern
# since you'll be able to reuse the same permit list between create and update. Also, you
# can specialize this method with per-user checking of permissible attributes.
def person_params
params.required(:person).permit(:name, :age)
end
end
Notice how, in the last lines, under the private keyword, the person_params method is defined, which declares the permitted fields to be assigned by the create and update methods on top. And it's the person_params that is used for updating - the valid example - instead of the raw params array.

Passing variables in RoR from html to model

I'm new to developing in Ruby on Rails and I'm stuck on a little project that I've been working on to understand RoR better. I am trying to make a little weather website and I'm having trouble sending user input to a model through a controller and to have that model use send back the correct information so that I can parse it and what not. I have not been able so far to send the user param along to the controller so that it will send out the right request. Here is my following code:
hourly.html.erb:
<%= form_tag('/show') do %>
<%= label_tag(:location, "Enter in your city name:") %>
<%= text_field_tag(:location) %>
<br />
<%= submit_tag "Check It Out!", class: 'btn btn-primary' %>
<% end %>
hourly_lookup_controller.rb:
class HourlyLookupController < ApplicationController
def show
#hourly_lookup = HourlyLookup.new(params[:location])
end
end
hourly_lookup.rb:
class HourlyLookup
def fetch_weather
HTTParty.get("http://api.wunderground.com/api/api-key/hourly/q/CA/#{:location}.xml")
end
def initialize
weather_hash = fetch_weather
assign_values(weather_hash)
end
def assign_values(weather_hash)
more code....
end
end
Any help or directions to some good examples or tutorials would be greatly appreciated. Thanks
If you want to send a variable to HourlyLookup, you'll need to do so:
class HourlyLookupController < ApplicationController
def show
#hourly_lookup = HourlyLookup.new(params[:location])
#hourly_lookup.fetch_weather
end
end
class HourlyLookup
attr_reader :location
def initialize(location)
#location = location
end
def fetch_weather
response = HTTParty.get("http://api.wunderground.com/api/cdb75d07a23ad227/hourly/q/CA/#{location}.xml")
parse_response(response)
end
def parse_response(response)
#parse the things
end
end

Resources