Conditional logic in Rails/ActionMailer for two ve

2019-09-12 09:14发布

问题:

Users are either readers or subscribers. When a new article is published, subscribers get a full text e-mail, readers get a teaser text. Assuming scopes in the model for readers/subscribers, is this right or do I need another conditional for each type of user?

if @article.valid?
  User.subscribers.each do |user|
    ArticleMailer.send_article_full(@article, user).deliver_now
  end
  User.readers.each do |user|
    ArticleMailer.send_article_teaser(@article, user).deliver_now
  end
  redirect_to :root, notice: "Article sent"
else
  render :new, notice: "There was an error"
end

回答1:

Given the fact, every user can either be a reader or subscriber, but can't be both simultaneously, and if you have correct scopes defined for readers and subscribers in the User model, then it should be fine. You don't need another conditional for each type of user because that would be redundant.