2016-03-03 82 views
1

我有一个电子邮件模型,供用户在添加或更新文章时注册以接收电子邮件通知。该电子邮件正常工作,但我收到一条错误消息,其中包含我在我的email.rb文件中生成的取消订阅方法。我发现在2012年发布的另一个stackoverflow问题中的取消订阅解决方案,但我没有看到如何正确工作解决方案。Rails取消订阅与ActionMailer的链接

电子邮件型号:

class Email < ActiveRecord::Base 
     validates :email, uniqueness: true 
     validates :email, presence: true 

     def unsubscribe 
     Email.find(params[:id]).update_attributes(permissions: false) 
     end 
    end 

文章型号:

class Article < ActiveRecord::Base 
     ... 
     has_many :emails 

     after_create :send_new_notifications! 
     after_update :send_update_notifications! 

     def send_update_notifications! 
     email = Email.where(permissions: true) 
     email.each do |email| 
      UpdatedArticleMailer.updated_article(email, self).deliver_later 
     end 
     end 

     def send_new_notifications! 
     email = Email.where(permissions: true) 
     email.each do |email| 
      ArticleNotificationMailer.new_article(email, self).deliver_later 
     end 
     end 
    end 

在更新文章电子邮件退订链接:

 <%= link_to "Unsubscribe", email_url(@email.unsubscribe) %> 

错误消息:

undefined local variable or method `params' for #<Email:0x007ff5c2955e88> 
    def unsubscribe 
    Email.find(params[:id]).update_attributes(permissions: false) 
    end 
end 

回答

1

不能调用从模型PARAMS。但是,您在生成视图时调用了取消订阅功能,我认为这不是我们的意图。您的设置应该是:

config/routes.rb

resources :emails do 
    get :unsubscribe, on: :member 
end 

这让你一个正确的路线,从你的观点命中。

app/controllers/email_controller.rb

def unsubscribe 
    email = Email.find params[:id] 
    email.update_attributes(permissions: false) 
    ... { handle errors, redirect on success, etc } ... 
end 

该处理控制的流程。

在视图中,链路变为:

unsubscribe_email_url(email) 

实质上,退订方法移动到控制器。应该很简单。请注意,此调用只是在用户单击链接时生成要调用的URL,并不实际进行调用。您目前的代码正在拨打电话。

+0

关于:会员,这是我声明的东西,例如电子邮件或这是从轨道上的东西? – jgrant

+0

我认为这工作,但我看到一个模板错误。我假设这是因为我没有在我的退订方法中设置句柄错误,重定向成功等? – jgrant

+1

对,您需要有一个名为unsubscribe.erb的视图,或者在成功时重定向它。 – GoGoCarl

1

params[:id]仅在控制器中可用。

你的link_to也没有意义,它看起来像你试图路由到你的模型,那些不能路由。它应该是控制器操作的链接,如EmailsController#Unsubscribe,并且该URL需要某种类型的ID。

class EmailsController < ApplicationController 
    def unsubscribe 
    if email = Email.find(params[:id]) 
     email.update_attribute(permissions: false) 
     render text: "You have been unsubscribed" 
    else 
     render text: "Invalid Link" 
    end 
    end 
end 

这并没有考虑到你可能想使用一个令牌,而不是一个ID的帐户,在这种情况下,请参阅本文使用MessageVerifier。

http://ngauthier.com/2013/01/rails-unsubscribe-with-active-support-message-verifier.html

+0

这个答案是不完整的,因为视图代码阻止任何工作。但这似乎是要在控制器而不是模型中完成的事情...... – GoGoCarl

+0

我认为你是对的。该模型根本不应该有取消订阅方法。这不是真正的商业逻辑。 – SacWebDeveloper