无法从URL获取id以在Rails ActionMailer的“To”字段中使用

时间:2016-06-20 18:18:57

标签: email ruby-on-rails-4

在我的Rails 4.2.6应用程序中,我有以下工作流程:

登录会员A搜索培训师,查看培训师B的个人资料,并决定向培训师B发送电子邮件以提问。来自会员A的原始电子邮件将发送到应用程序的域,该域将消息转发给培训师B.转发的消息包含“Reply_to”字段,因此培训师B可以直接回复成员A.搜索功能和交付从成员A到域的原始消息按预期工作。但是,我无法弄清楚如何从网址获取培训师的ID以将电子邮件转发给正确的培训师。

这就是我所做的,但没有成功......

通过培训师资料页面上的link_to传递培训师的ID(/views/trainers/show.html.erb):

<li id="up-next-email-trainer"><p><%= link_to 'Email trainer', new_email_path(:trainer => { :trainer_id => @trainer.id }), class: 'btn btn-primary btn-sm' %></p></li>

当会员点击上述链接时,该页面将重定向到以下网址的电子邮件表单:

http://localhost:3000/emails/new?trainer%5Btrainer_id%5D=5

其中5是此示例的教练的正确ID。我正在尝试使用request original_url来获取教练ID并将其存储在变量中。

但是,当成员填写表单并单击“发送电子邮件”按钮时,会触发以下错误:

ActiveRecord::RecordNotFound at /emails
Couldn't find Trainer with 'id'=s

看起来网址被切断了;训练师的身份证明没有通过。我无法弄清楚我做错了什么。

这是我的emails_controller.rb:

class EmailsController < ApplicationController
  before_filter :authenticate_user!
  before_action :get_trainer

  def new
    @email = Email.new  
  end

  def create
    @email = Email.new(email_params)

    if @email.valid?
      # Delivers email to app domain, then forward message
      EmailMailer.email_trainer(@email).deliver_now
      redirect_to user_path(current_user),
       notice: "Your message was sent successfully. Check your email account for a response soon."
    else
      render :new
    end
  end

  private

  def email_params
    params.require(:email).permit(:name, :email, :subject, :content)
  end

  def get_trainer
    params[:id] = request.original_url.last       
    @trainer = Trainer.find(params[:id])
  end
end

email_mailer.rb:

class EmailMailer < ApplicationMailer

  default :to => "........@gmail.com"

  def email_trainer(email)
        @email = email
        mail from: "#{ @email.name } <#{ @email.email }>",
         subject: @email.subject,
         body: @email.content,
         reply_to: @email.email  

     # Forwards email message to trainer
        get_trainer
        mail to: @trainer.email,
        subject: "An important message for trainer",
        body: "A member has sent you an email ....\nHere's the message:  '#{ @email.content }'\nReply directly to #{ @email.name } at #{ @email.email }.",
        reply_to: @email.email
    end
end

email.rb:

class Email
  include ActiveModel::Model
  attr_accessor :name, :email, :subject, :content

  ... validation code here ...
end

***编辑***** 电子邮件表单中的相关代码(/emails/new.html.erb):

  <%= f.input :name, :input_html => { :style => 'width: 50%' }, :placeholder => "Your name" %>
  <%= f.input :email, :input_html => { :style => 'width: 50%' }, :placeholder => "Your email address" %>
  <%= f.input :subject, :input_html => { :style => 'width: 50%' }, :placeholder => "Short subject line" %>
  <%= f.input :content, :as => :text, :input_html => { :id => 'email_textbox', :style => 'width: 50%' }, :placeholder => "Write your message here..." %>
</div>

<div class="actions">
  <%= f.submit 'Send email', class: "btn btn-primary" %>
</div>

****编辑 - 从帖子操作****

登录
    Started POST "/emails" for 127.0.0.1 at 2016-06-20 14:14:23 -0700
    ActiveRecord::SchemaMigration Load (2.2ms)  SELECT  "schema_migrations".* FROM "schema_migrations"
    Processing by EmailsController#create as HTML
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"YYOhw0Z9Fghoa5oeAke5KVcE2yHdLcUUDYvYjNDXPEDsS0i0QZNRoAncF2kmEjIBV+V9FrQbnQ2ve9mJoFllYA==", "email"=>{"name"=>"Jo Tester", "email"=>"jotester@example.com", "subject"=>"Testing", "content"=>"Testing mailer"}, "trainer"=>{"trainder_id"=>"5"}, "commit"=>"Send email"}
    User Load (2.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
    Trainer Load (2.0ms)  SELECT  "trainers".* FROM "trainers" WHERE "trainers"."id" = $1 LIMIT 1  [["id", nil]]
    Completed 404 Not Found in 323ms (ActiveRecord: 22.1ms)

    ActiveRecord::RecordNotFound - Couldn't find Trainer with 'id'=:
    activerecord (4.2.6) lib/active_record/core.rb:155:in `find'
    () home/ronald/projects/gym-app/app/controllers/emails_controller.rb:32:in `get_trainer'
    activesupport (4.2.6) lib/active_support/callbacks.rb:432:in `block in make_lambda'
    activesupport (4.2.6) lib/active_support/callbacks.rb:164:in `block in halting'
    activesupport (4.2.6) lib/active_support/callbacks.rb:504:in `block in call'
    activesupport (4.2.6) lib/active_support/callbacks.rb:504:in `call'
    activesupport (4.2.6) lib/active_support/callbacks.rb:92:in `__run_callbacks__'
    activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'
    activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
    actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in `process_action'
    actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:in `process_action'
    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'
    activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'
    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
    actionpack (4.2.6) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
    activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
    actionpack (4.2.6) lib/abstract_controller/base.rb:137:in `process'
    actionview (4.2.6) lib/action_view/rendering.rb:30:in `process'
    actionpack (4.2.6) lib/action_controller/metal.rb:196:in `dispatch'
    actionpack (4.2.6) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
    actionpack (4.2.6) lib/action_controller/metal.rb:237:in `block in action'
    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:43:in `serve'
    actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'
    actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'
    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'
    warden (1.2.6) lib/warden/manager.rb:35:in `block in call'
    warden (1.2.6) lib/warden/manager.rb:34:in `call'
    rack (1.6.4) lib/rack/etag.rb:24:in `call'
    rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
    rack (1.6.4) lib/rack/head.rb:13:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'
    rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
    rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'
    activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'
    activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
    activerecord (4.2.6) lib/active_record/migration.rb:377:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
    activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
    activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
    activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
    actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
    better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
    better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
    better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
    railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'
    railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'
    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'
    activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'
    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'
    railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'
    rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
    rack (1.6.4) lib/rack/runtime.rb:18:in `call'
    activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
    rack (1.6.4) lib/rack/lock.rb:17:in `call'
    actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'
    rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
    railties (4.2.6) lib/rails/engine.rb:518:in `call'
    railties (4.2.6) lib/rails/application.rb:165:in `call'
    rack (1.6.4) lib/rack/content_length.rb:15:in `call'
    thin (1.7.0) lib/thin/connection.rb:86:in `block in pre_process'
    thin (1.7.0) lib/thin/connection.rb:84:in `pre_process'
    thin (1.7.0) lib/thin/connection.rb:53:in `process'
    thin (1.7.0) lib/thin/connection.rb:39:in `receive_data'
    eventmachine (1.2.0.1) lib/eventmachine.rb:194:in `run'
    thin (1.7.0) lib/thin/backends/base.rb:73:in `start'
    thin (1.7.0) lib/thin/server.rb:162:in `start'
    rack (1.6.4) lib/rack/handler/thin.rb:19:in `run'
    rack (1.6.4) lib/rack/server.rb:286:in `start'
    railties (4.2.6) lib/rails/commands/server.rb:80:in `start'
    railties (4.2.6) lib/rails/commands/commands_tasks.rb:80:in `block in server'
    railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `server'
    railties (4.2.6) lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    railties (4.2.6) lib/rails/commands.rb:17:in `<top (required)>'
    () home/ronald/projects/gym-app/bin/rails:8:in `<top (required)>'
    spring (1.7.1) lib/spring/client/rails.rb:28:in `call'
    spring (1.7.1) lib/spring/client/command.rb:7:in `call'
    spring (1.7.1) lib/spring/client.rb:30:in `run'
    spring (1.7.1) bin/spring:49:in `<top (required)>'
    spring (1.7.1) lib/spring/binstub.rb:11:in `<top (required)>'
    () home/XX/projects/XX-XX/bin/spring:16:in `<top (required)>'
    () rails:3:in `<main>'

    Started POST "/__better_errors/4761d84c9ca9f7a7/variables" for 127.0.0.1 at 2016-06-20 14:14:24 -0700
    Trainer Load (1.3ms)  SELECT "trainers".* FROM "trainers"

3 个答案:

答案 0 :(得分:1)

变化:

def get_trainer
  params[:id] = request.original_url.last       
  @trainer = Trainer.find(params[:id])
end

为:

def get_trainer
  @trainer = Trainer.find(params[:trainer][:trainer_id])
end

永远不要超载参数

答案 1 :(得分:1)

添加:

.....
 your fields are here...
    <%= hidden_field_tag "trainer[trainer_id]", @trainer.id%>
</div>

<div class="actions">
.....

答案 2 :(得分:1)

控制器中的

EmailMailer.email_trainer(@email, @trainer).deliver_now

并在邮件中

def email_trainer(email, trainer)
    @email = email
    @trainer = trainer
    mail from: "#{ @email.name } <#{ @email.email }>",
     subject: @email.subject,
     body: @email.content,
     reply_to: @email.email  

    # Forwards email message to trainer
    mail to: @trainer.email,
    subject: "An important message for trainer",
    body: "A member has sent you an email ....\nHere's the message:  '#{ @email.content }'\nReply directly to #{ @email.name } at #{ @email.email }.",
    reply_to: @email.email
end

READY!