为Rails创建新闻稿列表

时间:2014-04-30 16:00:38

标签: ruby-on-rails

我已经看到这个问题在人们寻求帮助创建新闻通讯系统时提出了很多问题。

我有一个使用roadie gem的简报邮件设置。我需要帮助来弄清楚如何设置时事通讯的订户部分。我一直在邮件客户端手工制作新闻通讯,所以我有大约300名订阅者。

有人可以帮我设置代码,以便所有注册用户自动订阅时事通讯,我可以将我的300个电子邮件订阅者导入列表。还应该有取消订阅链接。援助对我和其他许多人都非常有帮助。

newsletter_mailer.rb:

class NewsletterMailer < ActionMailer::Base
  default from: "from@example.com"

  def weekly(email)
    @newsletter = newsletter
    @recipient = recipient
    mail to: email, subject: "New Dates Weekly"
  end

时事通讯控制器:

def send
 @newsletter = Newsletter.find(:params['id'])
 @recipients = Recipient.all
 @recipients.each do |recipient|
   Newsletter.newsletter_email(recipient, @newsletter).deliver
 end
end

用户控制器:

 def settings
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def profile
    @profile = User.profile
    @user = User.find(params[:id]) 
  end

  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.registration_confirmation(@user).deliver
      session[:user_id] = @user.id
      redirect_to root_url, notice: "Thank you for signing up!"
    else
      render "new"
    end
  end

  def show
    @user = User.find(params[:id])    
  end

    def edit
      @user = User.find(params[:id])
end

2 个答案:

答案 0 :(得分:2)

听起来你需要UserRecipient之间的一对一关系:

class User < ActiveRecord::Base
  has_one :recipient
  ...
end

class Recipient < ActiveRecord::Base
  belongs_to :user
  ...
end

然后在您的注册过程中,您只需要创建用户的收件人:

def create
  @user = User.new(user_params)
  if @user.save
    ...
    @user.create_recipient(:email => @user.email)
    ...
  else
    render "new"
  end
end

有关has_onecreate_association方法的详细信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

答案 1 :(得分:0)

这是经典的many-to-many关系 在Rails中,has_and_belongs_to_many通常将其称为habtm

了解人际关系的良好开端是RubyOnRail-Guides

基本上,您需要Newsletter模型和Subscriber模型以及表格newsletters_subscribers

class Newsletter < ActiveRecord::Base
  has_and_belongs_to_many :subscribers
end
class Subscriber < ActiveRecord::Base
  has_and_belongs_to_many :newsletters
end