0

I currently use .find_by_status(params[:status]) on my @tasks to find tasks that aren't closed or a sticky. (either 4,5).

def self.find_by_status(status)
  status = status.to_i
  if status == 0 then
    status = 1
  else
    status = status
  end
  if status == 1 || !status then
    Task.where(["STATUS NOT IN (4,5)"])
  else
    Task.where(:status => status)
  end
end

I also copied this for my tickets model too, to find only open tickets on the home page.

It's also accompanied by this

<% status_active = 1 %>
<% Task.new.statuses.each do |status| %>
  <li class="<%= if (params[:status].to_i || status_active) == status[0] then "active" end %>">
    <%= link_to status[1], :controller => params[:controller], :action => params[:action], :params => { :status => status[0] } %>
  </li>

I'm new to rails and I'm really struggling on refactoring this. I would probably prefer making those links into a drop down select filter, but that also I struggle with.

Any help is appreciated!

4

1 回答 1

1

这个片段:

def self.find_by_status(status)
  if status.to_i.zero?
    Task.where(["STATUS NOT IN (4,5)"])
  else
    Task.where(:status => status.to_i)
  end
end

与您上面的代码相同(在您转换后状态不可能为假to_i)。

您可以将视图代码清理为:

<% Task.new.statuses.each do |status| %>
  <li class="<%= 'active' if (params[:status].to_i || Task::STATUS_ACTIVE) == status[0] %>">
    <%= link_to status[1], :controller => params[:controller], :action => params[:action], :params => { :status => status[0] } %>
 </li>
<% end %>

我建议在模型中添加 STATUS_ACTIVE 作为常量,而不是将其编码到视图中。

此外,您通过参数指定控制器和操作这一事实很奇怪,但在不了解您的用例的情况下,我无法解决此问题。

于 2013-07-30T14:15:51.437 回答