Search code examples
ruby-on-railscontent-tag

content_tag outputs unexpected results


I have a method in my helper that loops through an array of activerecord objects and print the p tag for each item.

def tutor_work_exp(application)
        work_exps = application.work_exps
        if work_exps.present?
            work_exps.collect do |work_exp|
                content_tag :p do
                    work_exp.detail
                end
            end
        end
 end

I already read the rails api and somebody mentioned that I should not use the each method for content_tag, instead using the collect method. However, the result I got is an array of multiple strings like this:

["<p>25 years of selling stuffs</p>", "<p>15 years of selling books and electronic stuffs</p>"]

Not sure what I am doing wrong here. Here is how I am calling the helper method in my view(I am using haml by the way):

.item
    .content
      .header
        %p Work Exp:
      .description.m-mini--top
        = tutor_work_exp(@application)

Solution

  • Ok, I solved the problem by wrapping the content_tag method inside of the concat method like this:

    application.work_exps.each do |work_exp|
                    concat(content_tag(:p, work_exp.detail))
                end
    

    However, now it also prints the detail of all the activerecord objects, but I think it is another problem. The solution that I got is from thoughtbot

    Update: Ok, I got the reason why it also prints the object's details to the view. It is because of this line of code:

    =tutor_work_exp(@application)
    

    Basically, the each method will automatically returns the object itself that is calling it. In my case here, it is an array of activerecord objects, and the = will print whatever object is return and put it in the view. You can refer more here.

    So, I change it to:

    - tutor_work_exp(@application)
    

    It works perfect now.