在Views - rails4中使用创建的Helper方法

时间:2015-02-02 17:09:49

标签: ruby-on-rails ruby ruby-on-rails-4

我是铁杆新手所以非常感谢任何帮助或建议。我正在尝试调用一个名为" trackable_thing"的创建辅助方法。在我的视图文件中,但我收到错误消息:

wrong number of arguments (0 for 1)

[activities / index.html.erb]:我原来在我的观点文件中:

<h1>Activities</h1>

<% @activities.each do |activity| %>
  <% trackable_thing = activity.trackable %>
  <% if trackable_thing.respond_to? :name %>
    <% name = trackable_thing.name %>
  <% elsif trackable_thing.respond_to? :content %>  
    <% name = trackable_thing.content %>
  <% end %> </br>
  <%= link_to activity.owner.firstname, activity.owner if activity.owner %> created the event "<%= name %>"</br>
<% end %>

[activities_helper.rb]:但我想将视图中的以下逻辑代码转换为辅助方法并将其放在activities_helper.rb文件中 - 所以我编写了下面的帮助方法

activities/index.html.erb (code changed to a helper method as below)
<% trackable_thing = activity.trackable %>
<% if trackable_thing.respond_to? :name %>
   <% name = trackable_thing.name %>
<% elsif trackable_thing.respond_to? :content %>  
    <% name = trackable_thing.content %>
<% end %>

activities_helper.rb
module ActivitiesHelper
  #identifies if the trackable_thing is an event or comment
  def trackable_thing
    trackable_thing = activity.trackable
    if trackable_thing.respond_to? :name 
      name = trackable_thing.name
    elsif trackable_thing.respond_to? :content
      name = trackable_thing.content
    end
  end

[activities / index.html.erb]:我试图在视图中调用辅助方法,但我不确定如何。我打电话给它如下所示:

<h1>Activities</h1>
<% @activities.each do |activity| %>
  <% trackable_thing %>
  <%= link_to activity.owner.firstname, activity.owner if activity.owner %> created the event "<%= name %>"</br>
<% end %>

error message states: wrong number of arguments (0 for 1)

我也尝试过调用它,但是我收到了一个错误:

<h1>Activities</h1>
<% @activities.each do |activity| %>
  <% trackable_thing (link_to activity.owner.firstname, activity.owner if activity.owner %> created the event "<%= name %>")</br>
<% end %>

error message states: syntax error

非常感谢任何建议或帮助。

1 个答案:

答案 0 :(得分:1)

是什么ptd说,trackable_thing不知道什么是活动。使该方法获取一个参数,只要在调用它时传入活动,就可以将其命名为任何名称。