I implemented a RoR mailer with my Ruby on Rails Application and it worked well. But to my surprise, every time a mail is sent, other attributes from my database table is populated in my sent email which I do not want.
To have a diagramatic view of my problem, see this Mailer Preview image:
model(job.rb)
class Job < ActiveRecord::Base
def self.jobs_posted_12hrs_ago
where.not('stripeEmail' => nil).where.not('payola_sale_guid' => nil).where('created_at > ?', Time.now - 12.hours)
end
end
app/mailer/job_notifier.rb
class JobNotifier < ApplicationMailer
def send_post_email(job)
#user = User.where(:email => true).all
emails = #user.collect(&:email).join("#{';'}")
#jobs = job
#job = job
mail(:to => emails, :bcc => User.pluck(:email).uniq, :subject => 'New job posted on FarFlungJobs')
end
end
email template/view(send_post_email.html.erb)
I did iterate over my scope and populated just Comapny Name, Job Title, and Date. but when the email is previewed/sent, other attributes in the database are populated with it.
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<div>
<h3> Hi, new job just posted on FarFlungJobs.com! </h3>
</div>
<section>
<p>Fresh Job</p>
<hr>
<p>
<% jobs = Job.jobs_posted_12hrs_ago %>
<%= jobs.each do |job| %>
<section class="container">
<div class="row jobs">
<div class="col-md-4" style="font-size: 20px;"><strong><%= job.company_name %></strong></div>
<div class="col-md-4" style="font-size: 20px;"><%= link_to(job.title, job) %></div>
<div class="col-md-4 text-right" style="font-size: 20px; float: left;"><%= job.created_at.strftime('%d %B %y') %></div>
</div>
<%= render 'shared/two_breaks'%>
</section>
<% end %>
</p>
<p>Thanks for subscribing to FarFlungJobs once again. <%= jobs_url %> </p>
</section>
</body>
</html>
What can I do to make sure I only have just the specified attributes in my email template being sent, instead of it add all I dont want?
The problem is this line:
<%= jobs.each do |job| %>
Because of the <%= it will print out the result of the each statement, which is jobs.
Related
I've been looking for a bit and can't find or rather very well understand what to do, I'm sure its quite simple I'm just very new to Ruby and web apps, this one is in Sinatra for simplicity. I'd like to pass the #multiplication_table variable as well as the things the user puts into the inputs to the next results page so I can see if they put in the answers correctly but dont know how to, I think I know how to do this with a form_for but I dont know how to do that with already having a for loop.
This is my web.rb file
# web.rb
require 'sinatra'
def create_table(number)
possibles = [1,2,3,4,5,6,7,8,9,10,11,12]
int_set = possibles.shuffle
result = []
#answer_list = []
while int_set.length > 0
random_int = int_set[0]
string = (number.to_s + " x " + random_int.to_s)
int_set.delete(random_int)
if (random_int.to_s).length == 1
string += " = ______"
else
string += " = ______"
end
result << string
#answer_list << random_int.to_i * number.to_i
end
return result
end
get '/' do
#greeting = "Hi! Enter a number to generate a quick test."
erb :index
end
post '/results' do
erb :results
#multiplication_table
end
post '/' do
#multiplication_table = create_table(params[:int_to_generate])
#answers = #answer_list
erb :multiplication_table_page
end
and this is my multiplication_table_page.erb
<!-- multiplication_table_page.erb -->
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css">
</head>
<style>
h1 {text-align:center;}
p {text-align:center;}
.form-group {float: right; width: 100%;}
input {float: right;}
#submitall{width:100%;}
</style>
<body>
<div class="container">
<h1>Here is your table! Good luck.</h1>
<form action ="/results" method="POST" class="form-inline">
<% counter = 0 %>
<% #multiplication_table.each do |equation| %>
<input type="text" name = <%= "user_answer" + counter.to_s %> class="form-control">
<h2> <%= equation %> </h2>
<% counter += 1 %>
<% end %>
<p> </p>
<input id=submitall type="submit" class = "btn btn-primary">
</form>
<p> </p>
<p>Put another number in for another table</p>
<form action ="/" method="POST" class="form-inline">
<div class = "form-group">
<input type="submit" class = "btn btn-primary">
<input type="text" name ="int_to_generate" class="form-control">
</div>
</form>
<% #answers.each do |answer| %>
<p> <%= answer %> </p>
<% end %>
</div>
</body>
</html>
I am trying to send an email in rails 4 using sidekiq.
In this the values are not getting saved in the database instead only the form values are taken and the email is sent.
I have follwed this link https://www.codefellows.org/blog/how-to-set-up-a-rails-4-2-mailer-with-sidekiq
But the problem is that the email is not getting sent.
visitor_controller.rb
class VisitorsController < ApplicationController
def index
end
def contact
h = JSON.generate({ 'name' => params[:name],
'email' => params[:email],
'message' => params[:message] })
PostmanWorker.perform_async(h, 5)
# if instead of sidekiq I was just sending email from rails
#VisitorMailer.contact_email(#name, #email, #message).deliver
redirect_to :root
end
end
visitor_mailer.rb
class VisitorMailer < ApplicationMailer
def contact_email(name, email, message)
#name = name
#email = email
#message = message
mail(from: #email,
to: 'javier#badaboom.com',
subject: 'New Visitor\'s Email')
end
end
contact_email.html.erb
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1><%= #name %> (<%= #email %>)</h1>
<p>
<%= #message %>
</p>
</body>
</html>
index.html.erb
<h1>Email</h1>
<p>
<%= label_tag(:name, "My name is:") %>
<%= text_field_tag(:name) %>
</p>
<p>
<%= label_tag(:email, "My email address is:") %>
<%= text_field_tag(:email) %>
</p>
<p>
<%= label_tag(:message, "My Message is:") %>
<%= text_area_tag(:message) %>
</p>
<p>
<%= submit_tag("Send Email") %>
</p>
I want to as to why the email is not getting sent...
Thanks in advance!!!!
I am receiving the following error on a project of mine: First argument in form cannot contain nil or be empty. I am trying to create an edit page for my code. Fairly new with Rails and trying to learn without scaffolding.
Controller:
class BooksController < ApplicationController
def new
#book = Book.new
#authors = Author.all
end
def edit
#book = Book.find(params[:id])
end
def show
#Notice how the #books is plural here.
#books = Book.all
#authors = Author.all
##books = Book.where(id: params[:id])
end
#Create method will save new entries
def create
#book = Book.new(book_params)
#authors = Author.all
if #book.save
flash[:success] = "Book Added to Databse!"
redirect_to #book
else
render 'new'
end
end
private
#Note that this method will go up into the create method above.
def book_params
params.require(:book).permit(:title, :pub_date, :publisher, :author_id)
end
end
Model Page: (For Book)
class Book < ActiveRecord::Base
validates :title, :pub_date, :publisher, presence: true
validates :title, uniqueness: true
belongs_to :author
end
Model Page: (For Author)
class Author < ActiveRecord::Base
validates :name, presence: true
validates :name, uniqueness: true
has_many :books
end
Edit page:
<h1>Update a book entry</h2>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#book) do |f| %> **ERROR SEEMS TO BE RIGHT HERE!!!**
<%= render 'form' %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :pub_date %>
<%= f.text_field :pub_date, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :publisher %>
<%= f.text_field :publisher, class: 'form-control' %><br />
</div>
<div class="form-group">
<%= f.select(:author_id,
#authors.collect {|a| [ a.name, a.id ]},
{:include_blank => 'Please select an author'},
class: "form-control") %><br />
</div>
<%= f.submit 'Save Changes', class: "btn btn-primary" %>
<% end %>
</div>
</div>
Render form page (_form.html.erb)
<% if #book.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
<h2><%= pluralize(#book.errors.count, "error") %>
prohibited this entry from being saved:</h2>
<ul>
<% #book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
SHOW PAGE:
<div class="move">
<h1>Showing Book Titles:</h1>
</div><br />
<div class="row">
<% #books.each do |book| %>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<h2><%= book.title %></h2>
<h2><%= book.publisher %></h2>
<h2><%= book.pub_date %></h2>
<h2><%= book.author.name %></h2>
<h2><%= link_to "Edit", edit_path, class: "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
Here is my Log telling me what is wrong:
Started GET "/edit" for ::1 at 2015-08-14 16:49:17 -0400
Processing by BooksController#edit as HTML
Rendered books/edit.html.erb within layouts/application (2.2ms)
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (First argument in form cannot contain nil or be empty):
3: <div class="row">
4: <div class="col-md-6 col-md-offset-3">
5:
6: <%= form_for(#book) do |f| %>
7: <%= render 'form' %>
8:
9: <div class="form-group">
app/views/books/edit.html.erb:6:in `_app_views_books_edit_html_erb___525891009649529081_70260522100960'
I will say that I have deleted the first 14 books from my data base and so the first book start on ID 14. Not sure if that matters.
Finally, I have tried adding all of these different instance variables to my controller in the edit method:
##book = Book.where(id: params[:id])
##book = Book.find_by_id(params[:id])
##book = Book.all
##book = Book.find_by_id(params[:id])
#book = Book.new(book_params)
#When I use the two below lines,
there are no error pages but create a new entry.
##book = Book.new
##authors = Author.all
Any Help will be appreciated! Thank you for your time!!!
This error means that the first argument to form_for is a nil value (in this case #book). Most of the times I've seen this, it's due to malformed controller actions, but that doesn't look to be the case here. From what I can tell, it's one of two things:
You're trying to edit a Book that doesn't exist. Do a .nil? check on it before deciding to render the form, and render an error message (or redirect) instead.
Your routes are broken, and the edit action is not rendering the edit view. This is most likely not the case.
EDIT:
After updating with your template for show, this looks like your problem:
<%= link_to "Edit", edit_path, class: "btn btn-primary" %>
I see two problems with this (though I'll need to see the output of rake routes to verify). Firstly, you need to pass an argument to the edit path (without them, where would your params come from?). Secondly, the default route for this would be edit_book_path.
Try this:
<%= link_to "Edit", edit_book_path(book), class: "btn btn-primary" %>
Assuming book ID 14 is in your database, you should be able to navigate to localhost:3000/books/14/edit if you created it with something like resources :books (documentation here). If this doesn't work, either your routes are not defined correctly or book with ID 14 does not exist in your database.
On your show view, change the link_to line to:
<%= link_to 'Edit', edit_book_path(book), class: "btn btn-primary" %>
So two changes:
Again, assuming book is a Restful resource, when you run rake_routes, you should see the path to edit is edit_book_path.
You need to pass the book instance with the path so Rails knows which object you wish to edit.
I found the correct syntax here.
Hope this helps.
I'm using an example from Eric London http://ericlondon.com/2014/03/13/rails-4-submit-modal-form-via-ajax-and-render-js-response-as-table-row.html
And have adapted it slightly to my scenario:
While editing a Team (model) I want to pop a modal form to Add a new User. I can get this working i.e. when all fields are correct, the record is saved and the modal closes, but I am not getting errors back into the modal when there is a problem.
I also am uncertain how to structure the Create controller action correctly - this is definitely not right.
In the Users controller, create action (below) I can save the record as I expect, I have commented out the original code (I still need this - its the defaults for normal user management)
def create
#if params[:modal].nil? || params[:modal] == ''
# create! { users_url }
#else
respond_to do |format|
password = Devise.friendly_token.first(6)
#user.password = password
#user.password_confirmation = password
#user.external = true
if #user.save!
format.js { render action: 'show', status: :created, location: #user }
else
format.js { render json: #user.errors, status: :unprocessable_entity }
end
end
#end
end
the show.js.erb view
$('#new_user_modal').modal_success();
and the application.js code:
$(document).ready(function(){
$(document).bind('ajaxError', 'form#new_user', function(event, jqxhr, settings, exception){
// note: jqxhr.responseJSON undefined, parsing responseText instead
$(event.data).render_form_errors( $.parseJSON(jqxhr.responseText) );
});
});
(function($) {
$.fn.modal_success = function(){
// close modal
this.modal('hide');
// clear form input elements
// todo/note: handle textarea, select, etc
this.find('form input[type="text"]').val('');
// clear error state
this.clear_previous_errors();
};
$.fn.render_form_errors = function(errors){
$form = this;
this.clear_previous_errors();
model = this.data('model');
// show error messages in input form-group help-block
$.each(errors, function(field, messages){
$input = $('input[name="' + model + '[' + field + ']"]');
$input.closest('.form-group').addClass('has-error').find('.help-block').html( messages.join(' & ') );
});
};
$.fn.clear_previous_errors = function(){
$('.form-group.has-error', this).each(function(){
$('.help-block', $(this)).html('');
$(this).removeClass('has-error');
});
}
}(jQuery));
in the teams form I have the link and the modal definition:
<%# Added Bootstrap data modal attribute %>
<%= link_to 'Add an External User', '#new_user_modal', 'data-toggle' => 'modal', class: 'btn btn-default' %>
<%# Bootstrap modal markup. #see: http://getbootstrap.com/javascript/#modals %>
<div class="modal fade" id="new_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create new User</h4>
</div>
<div class="modal-body">
<%# Render the new person form (passing modal => true to enable remote => true) %>
<%= render 'users/new', modal: true %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
in the users/_new.html.erb view I have:
<% #user = User.new %>
<%= simple_form_for #user, remote: true, input_html: {role: :form, 'data-model' => 'user'} do |f| -%>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset>
<!-- username -->
<%= f.input :remote_id, label: "Payroll Code / Username" %>
<!-- basic settings -->
<div class="row">
<div class="col-md-6">
<%= f.input :first_name %>
</div>
<div class="col-md-6">
<%= f.input :last_name %>
</div>
</div>
<%= f.input :email %>
</fieldset>
<div class="actions">
<%= f.submit 'Submit', class: 'btn btn-primary' %>
</div>
<% end -%>
So, to sum up where I am at:
I want to add new users from a modal form while editing another
model
The approach above mostly works...
But is heinously ugly - it
feels wrong/messy and I am not happy with it.
It seems you don't have any 'help-block' classes on your form.
Try:
$.each(errors, function(field, messages){
$input = $('input[name="' + model + '[' + field + ']"]');
$span_error = $("<span></span>").addClass('help-block').html( messages.join(' & ') );
$form_input = $input.closest('.form-group').addClass('has-error').find('.form-control');
$span_error.insertAfter($form_input);
});
Instead of:
// show error messages in input form-group help-block
$.each(errors, function(field, messages){
$input = $('input[name="' + model + '[' + field + ']"]');
$input.closest('.form-group').addClass('has-error').find('.help-block').html( messages.join(' & ') );
});
Ive had a problem for a couple of days. I've tried every solotion thad i found on stackoverflow, but nothing worked...
Rails gives me an error when i try to add a new 'journey' (just a simple datapase entry): undefined method `journeys_index_path' for #<#:0x3d0b888>
Problem resolved!
The issue was the model name. It was Journeys but it should be journey ! The only thing I had to do is rename the modelfile in app/models. (i had to change the filename and the contents, pretty simple!
Oh and the model name is not the same as the database name.
Please check http://rubyonrailsthrissur.wordpress.com/2012/07/18/naming-conventions-while-creating-tables-in-rails/ for more naming rules
Routes.rb:
Fabulam::Application.routes.draw do
root "home#home"
resources :journeys
match 'auth/:provider/callback', to: 'sessions#create', via: 'get'
match 'auth/failure', to: redirect('/'), via: 'get'
match 'signout', to: 'sessions#destroy', via: 'get', as: 'signout'
end
journeys_controller (relevant part)
def index
#current_user ||= User.find(session[:user_id]) if session[:user_id]
#journey = Journeys.where(uid: current_user.uid)
end
def show
#journey = Journeys.find(params[:id])
end
def new
#journey = Journeys.new
end
new.html.erb (location = journeys/new.html.erb)
<!DOCTYPE html>
<html>
<body>
<div>
<h1> Maak hieronder een nieuwe reis aan! </h1>
<% form_for(#journey) do |f| %>
<p>
<%= f.label :name %><br/<
<%= f.text_field :name %>
</P>
<p>
<%f.submit "Dubmittt" %>
</p>
<% end %>
</div>
</body>
</html>
index.html.erb (location journeys/index.html.erb, this one is working fine)
<!DOCTYPE html>
<html>
<body>
<div id="user_nav">
<% if current_user %>
Signed in as <strong><%= current_user.name %></strong>!
<%= link_to "Sign out", signout_path, id: "sign_out" %>
<% else %>
<%= link_to "Sign in with Facebook", "/auth/facebook", id: "sign_in" %>
<% end %>
</div>
<div id="travels">
Hieronder al je reizen!
<% #journey.each do |journey| %>
<h2><%= link_to journey.name, journey %></h2>
<% end %>
</div>
<p><%= link_to "Add a new journey" , new_journey_path %> </P>
</body>
</html>
Rake routes
Prefix Verb URI Pattern Controller#Action
root GET / home#home
journeys GET /journeys(.:format) journeys#index
POST /journeys(.:format) journeys#create
new_journey GET /journeys/new(.:format) journeys#new
edit_journey GET /journeys/:id/edit(.:format) journeys#edit
journey GET /journeys/:id(.:format) journeys#show
PATCH /journeys/:id(.:format) journeys#update
PUT /journeys/:id(.:format) journeys#update
DELETE /journeys/:id(.:format) journeys#destroy
GET /auth/:provider/callback(.:format) sessions#create
auth_failure GET /auth/failure(.:format) redirect(301, /)
signout GET /signout(.:format) sessions#destroy
Am I missing something?
Thanks in advance!