ruby-on-rails – 为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

最佳答案 听起来你需要User和Recipient之间的一对一关系:

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_one方法(如create_association)的更多详细信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one.

点赞