[英]How to change to view helper method?
I am working on a app where you can add task etc. I know this is kind of weird but I just like to see how others would implement this. 我正在开发一个可以添加任务等的应用程序。我知道这有点奇怪,但我只想看看其他人如何实现这一点。 How would you change the following code into a helper method and use it?
您如何将以下代码更改为辅助方法并使用它?
The original code 原始代码
<h2>My Tasks</h2>
<% task = @work.tasks %>
<% if task.empty? %>
<%= link_to 'Create a new task', new_task_path %>
<% else %>
<%= render :partial => 'notes/note', :locals => {:note => @note} %>
<% end %>
My way of doing a helper method 我做辅助方法的方法
def task_check
task = @work.tasks
if task.empty?
link_to 'Create a new task', new_task_path
else
render :partial => 'notes/note', :locals => {:note => @note}
end
end
In my view 在我看来
<%= @work.task_check %>
Personally, I wouldn't extract this out at all, this is view logic and it belongs in the views. 就个人而言,我根本不会提取出来,这是视图逻辑,它属于视图。 It definitely doesn't belong in a model, but it could arguably be extracted into a helper.
它绝对不属于模型,但可以说它可以被提取到帮助器中。 I'd change it slightly:
我稍微改了一下:
<h2>My Tasks</h2>
<% if @work.tasks.blank? %>
<%= link_to 'Create a new task', new_task_path %>
<% else %>
<%= render :partial => 'notes/note', :locals => {:note => @note} %>
<% end %>
Calling blank?
打电话给
blank?
instead of empty?
而不是
empty?
will work even if @work.tasks
is nil
即使
@work.tasks
nil
也会有效
. 。
You can't define a helper in the model. 您无法在模型中定义帮助程序。 It won't have access to
render
, link_to
or any other controller or view methods. 它将无法访问
render
, link_to
或任何其他控制器或视图方法。 So just define your method almost exactly as is in a file in your helpers
directory, maybe application_helpers.rb
or work_helpers.rb
: 因此,只需在
helpers
目录中的文件中定义您的方法,可能是application_helpers.rb
或work_helpers.rb
:
def task_check(work, note)
task = work.tasks
if task.empty?
link_to 'Create a new task', new_task_path
else
render :partial => 'notes/note', :locals => {:note => note}
end
end
And then call it in your view like so: 然后在您的视图中调用它,如下所示:
<%= task_check(work, note) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.