Ruby on Rails helper prints out odd stuff

2019-07-26 03:47发布

I want to create a helper which iterates thru the list of user's communities and creates as many thumbnails as the number of comunities available. So I created these 2 helper methods

def print_admined_group_thumbs
    @user_groups_hash[:admined_groups].each {
        |group_hash|

        name            = group_hash[:name]
        group_id        = group_hash[:group_id]
        photo           = group_hash[:photo]
        members_count   = group_hash[:members_count].to_i

        concat(get_group_thumbnail_html(group_id, name, members_count, photo))
    }
end


# creates a small preview for the selected comunity group
def get_group_thumbnail_html(group_id, name, members_count, photo)
    content_tag(:div, :class => "col-md-55") do
       concat(content_tag( :div, :class => 'thumbnail') do
            concat(content_tag(:div, :class => 'image view view-first') do
                concat(image_tag(photo, :class => "group_thumb_image"))
                concat(content_tag(:div, :class => "mask") do
                    concat(content_tag :p, "Your text")  
                    concat(content_tag(:div, :class => "tools tools-bottom") do

                    end)    
                end)
                concat(content_tag(:div, :class => "caption") do
                    concat(content_tag(:p, name))
                end)
            end)
       end)
    end
end #end get_group_thumbnail_html 

So I simply add this call to my view

<%= print_admined_group_thumbs %>

It all works almost correctly and creates all thumbnails just like I want, except for one thing. It also prints out the entire contents of "group_hash" variable right after the thumbnails. Maybe I'm just too exhausted today, but I can't seem to figure out why? I'd be greateful if somebody helped me solve this problem and explain what am I doing wrong with it?

1条回答
祖国的老花朵
2楼-- · 2019-07-26 03:58

@some_hash.each {} automatically returns the hash after it completes. So your function print_admined_group_thumbs() adds your thumbnails to the template and returns the hash.

The problem is here:

<%= print_admined_group_thumbs %>

That = means "take whatever value is returned and add it to the template. So you're accidentally adding the hash to the template after printing the thumbnails to the template. You can easily fix it by removing the =:

<% print_admined_group_thumbs %>

This tells rails to run the function without adding its return value to the template.

查看更多
登录 后发表回答