编辑:
我是Rails的新手,正在尝试一些基本的东西,比如条件类。
在'show'视图中,我有一个元素,它根据库存可用性更改样式,但文本也相应地更改。
人们总是说控制器应该越小越好,但是在视图中放置这个条件也让人感觉很脏。这真的是最好的方法吗?
电流控制器:
def show
@tyre = Tyres::Tyre.find_by_id(params[:id])
if @tyre.in_stock
@availability = I18n.t("products.filter.other.in_stock")
@availability_class = 'i-check-circle color--success'
else
@availability = I18n.t("products.filter.other.not_in_stock")
@availability_class = 'i-cross-circle color--important'
end
end
编辑:
控制器:
def show
@tyre = Tyres::Tyre.find_by_id(params[:id])
if @tyre.in_stock
@availability_append = ".in_stock"
else
@availability_append = ".not_in_stock"
end
@availability = I18n.t("products.filter.other#{@availability_append}")
end
视图:
.xs-12.description__status
%i{class: (@tyre.in_stock? ? 'i-check-circle color--success' : 'i-cross-circle color--important')}
= @availability
你可以清理你的控制器 tyres_controller.rb
(我想)方法,
def show
@tyre = Tyre.find(params[:id]) # I believe you have a model named 'tyre'
end
然后,在您的myproject/app/helpers/
中将有一个名为tyres_helper.rb
的文件。在这里输入以下代码,
def tyre_availability(tyre) # it'll return an array with two values, first one is class name, second one is localized value
if tyre.in_stock
return 'i-check-circle color--success', I18n.t("products.filter.other.in_stock")
else
return 'i-cross-circle color--important', I18n.t("products.filter.other.not_in_stock")
end
end
,在视图中,您可以使用
.xs-12.description__status
%i{:class => tyre_availability(@tyre)[0]}
= tyre_availability(@tyre)[1]