Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionMailer link_to show action fails with "missing required keys: [:id]"

I'm trying to put a link to show action into view rendered by rails action mailer.

mailer.rb

class Mailer < ActionMailer::Base
  default from: "[email protected]"

  def catalog_download_request(email, catalog)
    @catalog = catalog

    mail({
         to: email
    })
  end

end

routes.rb

Rails.application.routes.draw do

  scope "(:locale)" do
    resources :catalogs, :path => I18n.t("routes.catalogs"), only: [:index, :show]
  end

end

development.rb:

config.action_mailer.default_url_options = { host: "http://localhost:3000" }
config.action_mailer.asset_host = "http://localhost:3000"

config.action_mailer.delivery_method = :smtp

config.action_mailer.smtp_settings = {
  address: "localhost",
  port: 1025
}

config.action_mailer.raise_delivery_errors = false

My model where I'm calling mailer:

class CatalogDownloadRequest < ActiveRecord::Base
  belongs_to :catalog

  after_create :send_mail

  private

  def send_mail
    Mailer.catalog_download_request(email, catalog).deliver
  end

end

That's what I tried in my view:

<%= link_to @catalog %>

error:

ActionView::Template::Error: No route matches {:action=>"show", :controller=>"catalogs", :format=>nil, :id=>nil, :locale=>#} missing required keys: [:id]

Another try:

<%= link_to catalog_url(@catalog) %>

error:

ActionView::Template::Error: No route matches {:action=>"index"}

I'm suspecting this is happening because my locale scope on routes.

If I use <%= link_to catalog_url(@catalog) %> in another view, it works.

Solved with:

<%= link_to catalog_url(:id => @catalog.id), catalog_url(:id => @catalog.id) %>
like image 703
William Weckl Avatar asked Sep 25 '14 20:09

William Weckl


1 Answers

The reason for ActionView::Template::Error: No route matches {:action=>"index"} is:

link_to requires two parameters (text and url) (api). You only passed one. After you pass the text as the first argument, it will work correctly.

If you really want, according to the document, you pass nil as the first argument and then url as the second one.

like image 88
lulalala Avatar answered Oct 20 '22 18:10

lulalala