Ruby on rails Rails部分-局部条件
我在一些邮件程序中使用了Rails部分中的以下代码,但我对我的解决方案不满意,感觉这远远不是最佳的 我有一封电子邮件 从我的邮件:Ruby on rails Rails部分-局部条件,ruby-on-rails,ruby-on-rails-4,partial-views,actionmailer,Ruby On Rails,Ruby On Rails 4,Partial Views,Actionmailer,我在一些邮件程序中使用了Rails部分中的以下代码,但我对我的解决方案不满意,感觉这远远不是最佳的 我有一封电子邮件 从我的邮件: def the_email_i_am_sending(user, inquiry, params = {}) get_variables(inquiry) #This also provides access to my `@user` object @contact_name = [params[:guest_last_name].to_s, " ", p
def the_email_i_am_sending(user, inquiry, params = {})
get_variables(inquiry) #This also provides access to my `@user` object
@contact_name = [params[:guest_last_name].to_s, " ", params[:guest_first_name].to_s].join
我总是有@user
,但有时一个特定的合作伙伴会调用我们的API,并使用上面定义的[:guest\u last\u name]
和[:guest\u first\u name]
的附加参数。这允许我将@contact\u name
定义为一个单独的实例变量
当这是.present?
即不是nil时,我希望在电子邮件的字段中呈现@contact\u name
,而不是从数据库中提取的@user.login
然后,我的mailer视图使用以下代码来决定它将呈现哪个部分
<% if @contact_name.present? %>
<%= render 'meet_your_guest_v3', tujia_guest: @contact_name %>
<% else %>
<%= render 'meet_your_guest_v3' %>
<% end %>
有更好的方法吗?关于如何处理控制器/邮件程序中的参数,您一定要遵循@Jon的建议。此外,您应该每次只将@contact_name传递给基础部分,而不管它是否存在,然后仅检查要渲染它的位置(如果存在)。这样可以跳过一个条件:
#email_view.html.erb
render 'meet_your_guest_v3', parnter_guest: @contact_name
_contact_name.html.erb
<% partner_guest.present? %>
...
#email_view.html.erb
呈现“会见您的客人”,客户:@contact\u name
_联系_name.html.erb
...
下一步可能是使用一个特殊的decorator对象,它将处理表示逻辑。它将检查联系人名称是从外部提供的还是从模型提供的,并为联系人名称呈现所需的html标记(或者它可以将其作为字符串返回)。请参阅以下使用draper gem的伪代码:
class MyController < ApplicationController
def send_mail
@user = User.find(...).decorate(
contact_name: [params[:guest_last_name].to_s, " ", params[:guest_first_name].to_s].join
)
MyMailer.the_email_i_am_sending(@user)
end
end
class MyMailer < ApplicationMailer
def the_email_i_am_sending(user)
@user = user
mail(to: ..., subject: ...)
end
end
class UserDecorator < Draper::Decorator
def contact_name_tag
if (contact_name.present?)
h.content_tag(:div, contact_name)
else
h.content_tag(:div, user_name)
end
end
end
#email_view.html.erb
<%= @user.contact_name_tag %>
class MyController
但是,如果表示逻辑不是很复杂,那么使用几个条件并可能将它们提取到基本rails帮助程序中是很好的,并且使用表示程序可能是一种过分的操作而不是将逻辑放在视图中,您可以将其放在控制器中。测试是否提供参数,并从
user
或params
为名称设置局部变量。然后在视图中输出数据。谢谢-这比需要两个条件的解决方案要干净得多。
class MyController < ApplicationController
def send_mail
@user = User.find(...).decorate(
contact_name: [params[:guest_last_name].to_s, " ", params[:guest_first_name].to_s].join
)
MyMailer.the_email_i_am_sending(@user)
end
end
class MyMailer < ApplicationMailer
def the_email_i_am_sending(user)
@user = user
mail(to: ..., subject: ...)
end
end
class UserDecorator < Draper::Decorator
def contact_name_tag
if (contact_name.present?)
h.content_tag(:div, contact_name)
else
h.content_tag(:div, user_name)
end
end
end
#email_view.html.erb
<%= @user.contact_name_tag %>