开发者

Refactor Rails 3 views - move logic to <model>_helper

I would like move the following from my View into the model's associated helper:

<%= link_to_unless params[:aged]=='0', "0", jobs_path(:aged => '0', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='30', "30", jobs_path(:aged => '30', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='60', "60", jobs_path(:aged => '60', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='90', "90", jobs_path(:aged => '90', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %>

I've tried this, but it causes an UNEXPECTED IDENTIFIER error (clearly I need to concatenate the results of the link_to_unless to the '|'):

link_to_unless params[:aged]=='0', "0", users_path(:aged=>'0',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='30', "30", users_path(:aged=>'30',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='60', "60", users_path(:aged=>'60',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='90', "90", users_path(:aged=>'90',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav])

It seems that I need to insert the results these helper methods into the HTML stream, but I'm not certain of the best approach.

Now that Rails 3 includes all helpers all the time (helpers :all) is there a way to instruc开发者_如何学Ct a model's view to only use the helper associated with the model? At this point, I'm adding the model's name into the name of the function--for example, 'jobs_sorted_column'.

** edit **

Refactored

jobs_helper:

  def posted_filter(bucket)

    link_to_unless params[:posted]==bucket, bucket, jobs_path(:posted =>bucket, :starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir])

  end

view:

[ <% ['0','30','60','90'].each do |bucket| %>
    <%= posted_filter(bucket) %> |
<% end %> ]

Issues:

  • Resulting output looks like [ 0 | 30 | 60 | 90 | ]. is there a simple fix to remove the 4th '|'?
  • It seems like there would be a more elegant way to pass the params to the route, including the one 'over-ridden' value (:posted=>bucket, in my example).


Try using collect and join, something like:

<%= ['0','30','60','90'].collect{ |x| "#{posted_filter(x)}" }.join(' | ') %>

See: Array #collect


You can do it even better:

def posted_filters(*args)
  args.collect { |bucket|
    link_to_unless(params[:posted]==bucket, bucket, jobs_path(:posted =>bucket, :starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir]))
  }.join(' | ').html_safe
end

And in your view code:

[ <%= posted_filters(0, 30, 60, 90) %> ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜