Sendgrid emails being sent without the template - ruby-on-rails

My sendgrid emails are being sent ok, but the template is never loaded. I have tried multiple times with many templates but they are never called, so there must be something wrong with my call.
This is the call from the controller:
AdminMailer.with( email: "xxxxxxxxx#gmail.com" , id:item.id, name: item.name, room: item.room.name).send_stock.deliver_later
This is my admin_mailer.rb
class AdminMailer < ApplicationMailer
def send_stock
mail(to: params[:email],
subject: 'Foto sin inventario',
body: 'email body',
delivery_method_options: {
api_key: ENV["SENDGRID_API"]
},
template_id: 'd-2d99d960ed47490497f1a99af32cd706',
dynamic_template_data:{
'id': params[:id],
'name': params[:name],
'room': params[:room]
}
)
end
and this is the output from rails:
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Performing ActionMailer::MailDeliveryJob (Job ID: d8927648-36ca-4e60-afd3-7fe6ea1b936f) from Async(mailers) enqueued at 2022-09-29T22:08:22Z with arguments: "AdminMailer", "send_stock", "deliver_now", {:params=>{:email=>"xxxxxxxxx#gmail.com", :id=>4, :name=>"foto 3 exclusive", :room=>"Sala 1"}, :args=>[]}
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] AdminMailer#send_stock: processed outbound mail in 1.0ms
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Delivered mail 6336175785e4_366932af97af0d39c27826#miguel.mail (7142.5ms)
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Date: Thu, 29 Sep 2022 17:08:23 -0500
From: xxxxxxxxx#gmail.com
To: xxxxxxxxx#gmail.com
Message-ID: <6336175785e4_366932af97af0d39c27826#miguel.mail>
Subject: Foto sin inventario
Mime-Version: 1.0
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
template-id: d-2d99d960ed47490497f1a99af32cd706
dynamic-template-data: {:id=>4, :name=>"foto 3 exclusive", :room=>"Sala 1"}
email body
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Performed ActionMailer::MailDeliveryJob (Job ID: d8927648-36ca-4e60-afd3-7fe6ea1b936f) from Async(mailers) in 7150.18ms
Cant find a lot of documentation regarding issues with templates.

The problem is that you supply this function call with the body property, which tells the SDK you want to send an email with this body. You need to omit this property if you want to use a template.
At least, that's how it works in the node.js SDK, and according to this sample code, I assume Ruby works similarly.

Related

How to send emails from Rails console: NoMethodError (undefined method `email' for nil:NilClass)

I'm trying to send newsletter to existing subscribers after I added to welcome email that send upon saved. Suppose I want to send this welcome email to exiting subscribers and I only need this functionality once. I'm seeking a way to send this emails from Rais console. I'm getting NoMethodError for 'email' please take a moment to review my code below.
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
default from: 'hello#example.com'
layout 'bootstrap-mailer'
def welcome_email
#newsletter = params[:newsletter]
#url = root_url
attachments.inline['welcome.png'] = File.read(Rails.root + 'welcome.png')
make_bootstrap_mail(
to: #newsletter.email,
subject: '🙋🏻‍♀️🦄 Welcome to My Newsletter!‍'
)
end
end
And then calling welcome_email from Rails console
$ rails c
Running via Spring preloader in process 10333
Loading development environment (Rails 6.0.3.3)
>> def self.send(newsletter)
>> #newsletters = Newsletter.all
>> #newsletters.each do |newsletter|
?> UserMailer.with(newsletter: #newsletter).welcome_email.deliver_now
>> end
>> end
=> :send
>> send(#newsletters)
Newsletter Load (0.5ms) SELECT "newsletters".* FROM "newsletters"
UserMailer#welcome_email: processed outbound mail in 9.6ms
Traceback (most recent call last):
5: from (irb):10
4: from (irb):10:in `rescue in irb_binding'
3: from (irb):3:in `send'
2: from (irb):4:in `block in send'
1: from app/mailers/user_mailer.rb:11:in `welcome_email'
NoMethodError (undefined method `email' for nil:NilClass)
When I run $ Newsletter.all it returns existing emails
Newsletter.all
Newsletter Load (0.4ms) SELECT "newsletters".* FROM "newsletters" LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Newsletter id: 1, email: "email-1#example.com", created_at: "2020-09-17 21:59:23", updated_at: "2020-09-17 21:59:23">, #<Newsletter id: 15, email: "email-2#example.com", created_at: "2020-09-18 01:20:46", updated_at: "2020-09-18 01:20:46">, #<Newsletter id: 16, email: "email-3#example.com", created_at: "2020-09-18 20:51:21", updated_at: "2020-09-18 20:51:21">]>
How can I pass these emails to welcom_email correctly?
I'm using bootstrap-email gem and it is sending welcome_email upon newsletter.save correctly.
# app/controllers/newsletters_controller.rb
class NewslettersController < ApplicationController
def new
#newsletter = Newsletter.new
end
def create
#newsletter = Newsletter.new(newsletter_params)
if #newsletter.save
UserMailer.with(newsletter: #newsletter).welcome_email.deliver_now
flash[:success] = "You've successfully subscribed to our newsletter. You will recive confirmation email with instractions in a few minuets."
redirect_to root_path
else
redirect_to root_path, alert: "Email address already subscribed to newsletter or incorrect format."
end
end
private
def newsletter_params
params.require(:newsletter).permit(:email)
end
end
Here is development log for sending email from create method
Started POST "/newsletters" for ::1 at 2020-09-20 13:00:02 -0700
Processing by NewslettersController#create as HTML
Parameters: {"authenticity_token"=>"bSR/L+5IQB027LeCv42DX3tw120NkLPmNHMPGqFSiOK66ct8Z2N7Yx5XbBVMmbFNgVoKKoSQCPaOoKWkC+AHvg==", "newsletter"=>{"email"=>"email-4#example.com"}, "commit"=>"Subscribe to Newsletter!"}
[1m[35m (0.2ms)[0m [1m[35mBEGIN[0m
↳ app/controllers/newsletters_controller.rb:9:in `create'
[1m[36mNewsletter Exists? (1.0ms)[0m [1m[34mSELECT 1 AS one FROM "newsletters" WHERE LOWER("newsletters"."email") = LOWER($1) LIMIT $2[0m [["email", "email-4#example.com"], ["LIMIT", 1]]
↳ app/controllers/newsletters_controller.rb:9:in `create'
[1m[36mNewsletter Create (2.4ms)[0m [1m[32mINSERT INTO "newsletters" ("email", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"[0m [["email", "email-4#example.com"], ["created_at", "2020-09-20 20:00:03.020983"], ["updated_at", "2020-09-20 20:00:03.020983"]]
↳ app/controllers/newsletters_controller.rb:9:in `create'
[1m[35m (0.7ms)[0m [1m[35mCOMMIT[0m
↳ app/controllers/newsletters_controller.rb:9:in `create'
Rendering user_mailer/welcome_email.html.erb within layouts/bootstrap-mailer
Rendered user_mailer/welcome_email.html.erb within layouts/bootstrap-mailer (Duration: 7.8ms | Allocations: 6866)
Rendering user_mailer/welcome_email.text.erb
Rendered user_mailer/welcome_email.text.erb (Duration: 0.7ms | Allocations: 128)
UserMailer#welcome_email: processed outbound mail in 531.1ms
Delivered mail 5f67b4c38a48f_5ba63fd8c7a7684c6726#PC.local.mail (3513.0ms)
Date: Sun, 20 Sep 2020 13:00:03 -0700
From: hello#example.com
To: email-4#example.com
Message-ID: <5f67b4c38a48f_5ba63fd8c7a7684c6726#pc.local.mail>
Subject: =?UTF-8?Q?=F0=9F=99=8B=F0=9F=8F=BB=E2=80=8D=E2=99=80=EF=B8=8F=F0=9F=A6=84?=
=?UTF-8?Q?_Welcome_to_Newsletter!=E2=80=8D?=
Mime-Version: 1.0
Content-Type: multipart/related;
boundary="--==_mimepart_5f67b4c3d687_5ba63fd8c7a7684c67176";
charset=UTF-8
Content-Transfer-Encoding: 7bit
I replaced #newsletter with newsletter in UserMailer.with(newsletter: #newsletter).welcome_email.deliver_now line and then it worked.
From rails console
>> def self.send(newsletter)
>> #newsletters = Newsletter.all
>> #newsletters.each do |newsletter|
?> UserMailer.with(newsletter: newsletter).welcome_email.deliver_now
>> end
>> end
>> send(#newsletters)
[1m[36mNewsletter Load (0.6ms)[0m [1m[34mSELECT "newsletters".* FROM "newsletters"[0m
Rendering user_mailer/welcome_email.html.erb within layouts/bootstrap-mailer
Rendered user_mailer/welcome_email.html.erb within layouts/bootstrap-mailer (Duration: 27.2ms | Allocations: 6172)
Rendering user_mailer/welcome_email.text.erb
Rendered user_mailer/welcome_email.text.erb (Duration: 0.5ms | Allocations: 129)
UserMailer#welcome_email: processed outbound mail in 876.2ms
Delivered mail 5f67c372b64d3_76d23ff23d83204c25077#PC.local.mail (518.1ms)
# Welcome email sent to each email in Newsletter
Unlike create method in my newsletter controller, my code in the console doesn't have #newsleeter as #mu is too short pointed out in the comment.
Voila! We now know how to send emails from rails console manually for all existing emails in the database.

ruby on rails 4 - devise - send_reset_password_instructions - reset password - Reset password token is invalid

I am using ruby on rails version '4.2.4' and devise 4.0.0
gem 'rails', '4.2.4'
devise (4.0.0)
bcrypt (~> 3.0)
orm_adapter (~> 0.1)
railties (>= 4.1.0, < 5.1)
responders
warden (~> 1.2.3)
Taking over some code made from someone, they have implemented reset password but didnt quite work. I am trying to solve it.
from the console, I tried to use this:
> u = User.first
> u.send_reset_password_instructions
this is console output:
[15] pry(main)> u.send_reset_password_instructions
Devise::Mailer#reset_password_instructions: processed outbound mail in 37.9ms
Sent mail to testme#gmail.com (6024.6ms)
Date: Sun, 20 May 2018 12:13:23 +0800
From: "My Support" <support#my.org>
Reply-To: "Harta.Org Support" <support#my.org>
To: testme#gmail.com
Message-ID: <5b00f5e3e4f8f_9da3ff91bc336ac799e0#Macbook.local.mail>
Subject: Reset password instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Hello testme#gmail.com!</p>
<p>Someone has requested a link to change your password. You can do this through the link below.</p>
<p>Change my password</p>
<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>
=> "qpkCBYwZzmqprudst1oq"
the email is received, however navigating to the page (http://localhost:3000/users/password/edit?reset_password_token=qpkCBYwZzmqprudst1oq) and inserting the new password has this error
1 error prohibited this user from being saved:
Reset password token is invalid
I checked there is some token generated in the User record:
reset_password_token: "23837a8b05a8249ac4edf5e3e6b6e8f922277ef409e693cd802bc1707b0838b7",
reset_password_sent_at: Sun, 20 May 2018 04:13:23 UTC +00:00,
this matches the debug output below:
Started PUT "/users/password" for ::1 at 2018-05-20 12:52:04 +0800
Processing by Devise::PasswordsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NtKJ86mslX4tQ7arV+FcO+5dU4BCvD1A0GRzs9YwqG1h+vsdbEh9FXW+VQLJMnNsTXuJ0VMmC+f9v8/uW56CMQ==", "user"=>{"reset_password_token"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
localhost
Set current domain
{"reset_password_token":"23837a8b05a8249ac4edf5e3e6b6e8f922277ef409e693cd802bc1707b0838b7"}
Rendered users/shared/_links.html.erb (0.3ms)
Rendered users/passwords/edit.html.erb within layouts/application (9.5ms)
Rendered layouts/_navigation.html.slim (2.0ms)
Rendered layouts/_messages.html.slim (0.1ms)
Completed 200 OK in 243ms (Views: 199.9ms | ActiveRecord: 0.0ms)
What is the problem, how to debug (like how do i know if the token is correct) and solve this ?
I manage to override Devise::PasswordsController to change the password devise in controller/users/password_controller. However, I want to debug this now, recoverable.rb ? How can I override recoverable.rb ? I want to see how it works in this method:
def reset_password_by_token(attributes={})

TypeError when sending email in ActionMailer

I am trying to set up a mailer in my Rails application that sends an email to users of the system. When I try to send the email, it is getting processed and the completed emails are being put in the log but near the end of the process I am getting the error:
TypeError (no implicit conversion of Symbol into Integer):
app/controllers/users_controller.rb:58:in `email'
I am not receiving the email so it seems like the error is occurring when the email is being created or delivered.
The following is my configuration and the code calling the email:
Production.rb
# Mailer Configuration
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'corp-alt-14', # Local mail server on the network
:port => 25,
:openssl_verify_mode => :none
}
users_controller.rb
def email
user = User.find(params[:user_id])
UserMailer.welcome_email(user).deliver_now # Line 58
render nothing: true #Ajax request should not update the page
end
user_mailer.rb
class UserMailer < ApplicationMailer
def welcome_email(user)
#user = user
mail(to: #user.email, subject: 'Welcome Test Email')
end
end
application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "DoNotReply#example.com"
layout 'mailer'
end
production.log
I, [2015-07-08T15:55:08.569007 #8496] INFO -- : Started GET "/users/email?user_id=2" for ::1 at 2015-07-08 15:55:08 -0400
I, [2015-07-08T15:55:08.571007 #8496] INFO -- : Processing by UsersController#email as JS
I, [2015-07-08T15:55:08.571007 #8496] INFO -- : Parameters: {"user_id"=>"2"}
D, [2015-07-08T15:55:08.572007 #8496] DEBUG -- : [1m[36mUser Load (0.0ms)[0m [1mEXEC sp_executesql N'SELECT [users].* FROM [users] WHERE [users].[id] = #0 ORDER BY [users].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY', N'#0 int', #0 = 2[0m [["id", "2"]]
I, [2015-07-08T15:55:08.575007 #8496] INFO -- : Rendered user_mailer/welcome_email.html.erb within layouts/mailer (1.0ms)
I, [2015-07-08T15:55:08.575007 #8496] INFO -- : Rendered user_mailer/welcome_email.text.erb within layouts/mailer (0.0ms)
D, [2015-07-08T15:55:08.577007 #8496] DEBUG -- :
UserMailer#welcome_email: processed outbound mail in 4.0ms
I, [2015-07-08T15:55:08.614007 #8496] INFO -- :
Sent mail to evan_frisch#example.com (36.0ms)
D, [2015-07-08T15:55:08.614007 #8496] DEBUG -- : Date: Wed, 08 Jul 2015 15:55:08 -0400
From: DoNotReply#example.com
To: evan_frisch#example.com
Message-ID: <559d801c8d1d7_21301f76380640db#FRISCHE.mail>
Subject: Welcome Test Email
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_559d801c8ca07_21301f7638063943";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_559d801c8ca07_21301f7638063943
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
This is a test email.
Hello Evan
----==_mimepart_559d801c8ca07_21301f7638063943
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<body>
<h1>This is a test email</h1>
<p>Hello Evan</p>
</body>
</html>
----==_mimepart_559d801c8ca07_21301f7638063943--
I, [2015-07-08T15:55:08.615007 #8496] INFO -- : Completed 500 Internal Server Error in 44ms
F, [2015-07-08T15:55:08.623007 #8496] FATAL -- :
TypeError (no implicit conversion of Symbol into Integer):
app/controllers/users_controller.rb:58:in `email
I am using Ruby 2.0.0 and Rails 4.2.0.
As far as I can see, there is no symbol that is being converted into an integer in my code. I have attempted to debug into the mailer code to see where the error was being raised but I could not find it. I don't know if there is something wrong with the code I have or if my config is incorrectly done. I have confirmed the mail server's name and port so that data is correct at the least. Any suggestions would be greatly appreciated.
As it turns out when you aren't using SSL and do not have an SMTP just setting :openssl_verify_mode => :none is not enough. By adding :enable_starttls_auto => false my error disappeared and the emails started sending. It normally defaults to true which apparently caused errors with not using a secure user.
To note my final SMTP settings were:
config.action_mailer.smtp_settings = {
:address => 'corp-alt-14',
:port => 25,
:openssl_verify_mode => :none,
:enable_starttls_auto => false
}

Rails ActionMailer preview not rendering in development

I've set up account activation emails. When I go to the preview page:
http://localhost:3000/rails/mailers/agent_mailer/account_activation
The view is blank. The page correctly formats the to/from addresses and the subject, but there is no body to the email.
Here are some of the server logs:
Started GET "/rails/mailers/agent_mailer/account_activation?part=text%2Fhtml" for ::1 at 2015-05-19 17:42:27 -0700
Processing by Rails::MailersController#preview as HTML
Parameters: {"part"=>"text/html", "path"=>"agent_mailer/account_activation"}
Agent Load (0.5ms) SELECT "agents".* FROM "agents" ORDER BY "agents"."id" ASC LIMIT 1
Rendered agent_mailer/account_activation.html.erb within layouts/mailer (0.1ms)
Rendered agent_mailer/account_activation.text.erb within layouts/mailer (0.0ms)
Rendered agent_mailer/account_activation.html.erb within layouts/mailer (0.1ms)
Rendered agent_mailer/account_activation.html.erb within layouts/mailer (0.0ms)
AgentMailer#account_activation: processed outbound mail in 43.5ms
Rendered text template (0.0ms)
Completed 200 OK in 49ms (Views: 1.8ms | ActiveRecord: 0.5ms)
I don't understand why it's rendering account_activation.html.erb 3 times.
I've been banging my head against a wall for 6 hours so any help would be really appreciated :)
Here are the relevant files.
app/mailers/application_mailer.rb:
class ApplicationMailer < ActionMailer::Base
default from: "admin#example.com"
layout 'mailer'
end
app/views/layouts/mailers.html.erb:
<html>
<body>
<%= yield %>
</body>
</html>
app/views/layouts/mailers.text.erb:
<%= yield %>
app/mailers/agent_mailer.rb:
class AgentMailer < ApplicationMailer
def account_activation(agent)
#agent = agent
mail from: "admin#example.com"
mail to: agent.email
mail subject: "Agent Account Activation"
end
end
app/views/agent_mailer/account_activation.html.erb:
<p>Welcome to Example! Click on the link below to activate your agent account: </p>
<%= link_to "Activate", edit_agent_account_activation_url(#agent.activation_token, email: #agent.email) %>
app/views/agent_mailer/account_activation.text.erb:
Welcome to Example! Click on the link below to activate your agent account:
<%= edit_agent_account_activation_url(#agent.activation_token, email: #agent.email) %>
I've tried putting some extra text in the layouts/mailers file but that doesn't render either. So I thought then that the layouts weren't being properly called. However, when I put layout 'something' in the application_mailer.rb I got an error for a missing layout. I commented out #agent = agent and got an nil exception at the #agent.activation_token.
So it seems like the layout and the template are being processed, but for some reason they aren't being rendered.
You can't call 'mail' so many times.
app/mailers/agent_mailers.rb:
class AgentMailer < ApplicationMailer
def account_activation(agent)
#agent = agent
mail from: "admin#example.com", to: agent.email, subject: "Agent Account Activation"
end
end

Why is my rails controller rolling back my ajax commit?

I am having a mysterious problem with the controller receiving my ajax request but not saving it in the database. In my server log I see:
Started POST "/collection_maps" for 127.0.0.1 at 2014-07-07 07:14:04 -0600
Processing by CollectionMapsController#create as */*
Parameters: {"collection_id"=>"2", "manufacturer_id"=>"1", "package_id"=>"14"}
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered collection_maps/create.js.erb (1.9ms)
Completed 200 OK in 19.2ms (Views: 4.8ms | ActiveRecord: 0.2ms)
127.0.0.1 - - [07/Jul/2014 07:14:04] "POST /collection_maps HTTP/1.1" 200 - 0.0627
The response I receive in the browser from my create.js.erb file indicates the parameters are null -- but as you can see above, they're clearly there.
(The response comes only as text, the browser doesn't execute the code, but that's another problem. I think.)
// Create a list of errors
var errors = $('<ul />');
errors.append('<li>Package can\'t be blank</li>');
errors.append('<li>Manufacturer can\'t be blank</li>');
errors.append('<li>Collection can\'t be blank</li>');
// Display errors on form
$("#collection-response").html(errors).show();
When I try to create the record in the console, using the same parameters, it works:
irb(main):006:0> c = CollectionMap.new("collection_id"=>"2", "manufacturer_id"=>"1", "package_id"=>"12")
=> #<CollectionMap id: nil, package_id: 12, manufacturer_id: 1, collection_id: 2, created_at: nil, updated_at: nil>
irb(main):007:0> c.save
(0.1ms) begin transaction
SQL (5.7ms) INSERT INTO "collection_maps" ("collection_id", "created_at", "package_id", "manufacturer_id", "updated_at") VALUES (?, ?, ?, ?, ?) [["collection_id", 2], ["created_at", Mon, 07 Jul 2014 06:38:47 UTC +00:00], ["package_id", 12], ["manufacturer_id", 1], ["updated_at", Mon, 07 Jul 2014 06:38:47 UTC +00:00]]
(1.2ms) commit transaction
=> true
irb(main):008:0> c
=> #<CollectionMap id: 6, package_id: 12, manufacturer_id: 1, collection_id: 2, created_at: "2014-07-07 06:38:47", updated_at: "2014-07-07 06:38:47">
I thought maybe it had something to do with CRSF protection (though I don't have user sessions) so I added a skip_filter. Here's my controller code:
class CollectionMapsController < ApplicationController
respond_to :js, :html
skip_before_filter :verify_authenticity_token
# POST /collection_maps
# POST /collection_maps.xml
def create
#collection_map = CollectionMap.new(params[:collection_map])
flash[:notice] = "Collection map successfully added" if #collection_map.save
respond_with( #collection_map, :layout => !request.xhr?)
end
Here's my ajax code:
$.ajax({ url: '<%="#{collection_maps_path}"%>',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',
'<%="#{form_authenticity_token}"%>')},
dataType: "js",
data: {'collection_id' : this.value,
'manufacturer_id' : $("#remedy_manufacturer_id option:selected").val(),
'package_id' : $("#remedy_package_id option:selected").val()},
});
And finally, my model:
class CollectionMap < ActiveRecord::Base
belongs_to :manufacturer
belongs_to :package
belongs_to :collection
validates_presence_of :package_id, :manufacturer_id, :collection_id
attr_protected :created_at
attr_protected :updated_at
attr_accessible :package_id, :manufacturer_id, :collection_id
end
I am totally baffled, so help would be much appreciated.
UPDATE: The reason my browser was not executing the javascript returned by the controller was because I had dataType: "js" in the ajax request. Should be dataType: "script". Be careful where you cut and paste from!
Your AJAX request is sending back the three parameters you need, but your controller action is looking for them nested below a :collection_map key. You can change your controller to this:
def create
#collection_map = CollectionMap.new(params)
flash[:notice] = "Collection map successfully added" if #collection_map.save
respond_with( #collection_map, :layout => !request.xhr?)
end
Or change your AJAX request to this:
$.ajax({ url: '<%="#{collection_maps_path}"%>',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',
'<%="#{form_authenticity_token}"%>')},
dataType: "js",
data: {'collection_map': {'collection_id' : this.value,
'manufacturer_id' : $("#remedy_manufacturer_id option:selected").val(),
'package_id' : $("#remedy_package_id option:selected").val()}},
});
Changing the AJAX request is probably preferable; nesting the parameters below a single key is more "Rails-like"/idiomatic.
you are also mixing attr_accessible and attr_protected. Choose One. Or if this is a newer Rails (4.0 + ) project, use the the new params methodology by creating a method like 'collection_map_params' for 'protection' in your CollectioMapsController.

Resources