将Ruby代码从视图中提取到Helper中

时间:2021-05-15 21:26:59

I have some ruby code in a view and it works great but I know that's not the correct way to do it so want to put it into a helper method (thanks @SimoneCarletti). I'm having some difficulty with that and usually I find people on here 10000x smarter than me who are excellent Rubyists.

我在视图中有一些ruby代码并且它工作得很好但是我知道这不是正确的方法,所以想把它放到一个帮助方法中(感谢@SimoneCarletti)。我遇到了一些困难,通常我发现这里10000人比我优秀的Rubyist更聪明。

Here is the code that I want to put into a helper

这是我想要放入帮助器的代码

product_feed_item.voters_who_voted.map(&:full_name).join(("<br />").html_safe)

Here is the method below in my user model to get the user's product_feed

以下是我的用户模型中的方法,以获取用户的product_feed

def product_feed
  Design.from_users_followed_by(self).to_a.concat Product.from_users_followed_by(self).to_a
end

The controller for this view is

此视图的控制器是

@product_feed_items = current_user.product_feed
@product_feed_items.sort! {|t1, t2| t2.created_at <=> t1.created_at}

respond_to do |format|
  @product_feed_items = @product_feed_items.paginate(:page => params[:page], :per_page => 20)
  format.html
  format.json { render json: @product_feed_items }
end

and the View is

和视图是

<%= render partial: "shared/product_feed_item", collection: @product_feed_items %>

Where the partial contains the first block of code I want to extract into a method.

其中partial包含我要提取到方法中的第一个代码块。

How can I put this into a method?? If you need me to clarify or add anything to help please just let me know.

我怎么能把它放到一个方法?如果您需要我澄清或添加任何帮助,请告诉我。

Thanks in advance for helping! Happy Holidays!

在此先感谢您的帮助!节日快乐!

2 个解决方案

#1


1  

Its as simple as below unless i am missing something

它简单如下,除非我遗漏了一些东西

def voter_full_names(product_feed_item)
  product_feed_item.voters_who_voted.map(&:full_name).join(("<br />").html_safe
end

And in your view

在你看来

<%= voter_full_names(product_feed_item)%>

#2


0  

You can try to use decorator. With Draper decorators, you can wrap your models with presentation-related logic to organize.

你可以尝试使用装饰器。使用Draper装饰器,您可以使用与表示相关的逻辑来组织模型。

https://github.com/drapergem/draper

#1


1  

Its as simple as below unless i am missing something

它简单如下,除非我遗漏了一些东西

def voter_full_names(product_feed_item)
  product_feed_item.voters_who_voted.map(&:full_name).join(("<br />").html_safe
end

And in your view

在你看来

<%= voter_full_names(product_feed_item)%>

#2


0  

You can try to use decorator. With Draper decorators, you can wrap your models with presentation-related logic to organize.

你可以尝试使用装饰器。使用Draper装饰器,您可以使用与表示相关的逻辑来组织模型。

https://github.com/drapergem/draper