0

我试图最好地了解如何将铁路助手与 haml 视图一起使用。

我有一个最初包含此逻辑的视图

=   fund_levels_last(i, @fund_level_count) ? ( link_to "add new level", ad, {class: 'button orange sm'} ) : ( link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class => 'button orange sm', :method => :delete, :remote => true, :confirm => t('q.are_you_sure')} )

为了尽可能保持视图的代码简洁,我一直在尝试将此逻辑移至帮助程序。

   def fund_levels_last(i, flcount)
     if i ==  flcount
       true
     else
       false
     end
   end

   def fund_levels_btn(i, flcount)
     if self.fund_levels_last(i, flcount)
       link_to "add new level", ad, {class: 'button orange sm'}
     else
       link_to "remove", accounts_ad_fund_level_path(ad, fl.object.id), {:class => 'button orange sm', :method => :delete, :remote => true, :confirm => t('q.are_you_sure')}
     end
   end

但是,在帮助程序中,我无权访问视图中的变量和对象(广告、对象、fl 等)。我想我可以将所有这些都传递给辅助方法,但不知何故,这似乎太复杂了,我觉得我在这里走错了路。我在视图中的单行代码似乎最终成为助手中的 15 行代码......

将此逻辑从视图移动到帮助器的最简单方法是什么?

4

2 回答 2

3

顺便说一句,方法

def fund_levels_last(i, flcount)
  if i ==  flcount
    true
  else
    false
  end
end

可能只是:

def fund_levels_last(i, flcount)
  i ==  flcount
end

而且,返回布尔值的方法通常以 a 结尾,?所以它会变成def fund_levels_last?(i, flcount)

于 2012-10-28T16:31:23.593 回答
2

如果您的代码足够简单,您可能实际上需要一个部分代码。然后你可以像这样传递代码/变量:

<%= render :partial => 'funds/partial_view', :locals => { :var => variable } %>

但如果你需要一个助手,你将不得不作为参数传递:

def funds_helper(var) //do something interesting end

但是,没有理由将您的所有逻辑都排除在视图之外,而是将其分解为部分:

在控制器中: @fund_level = fund_levels_last(i, @fund_level_count)

鉴于: <%= @fund_level ? render :partial => 'funds/add_new_level' : render :partial => 'funds/remove_level' %>

然后让你的部分观点有正确的观点。

于 2012-10-28T20:00:22.333 回答