How to display ROR 5 ActiveRecord pluck as String in html.erb

762 Views Asked by At

In html.erb I have:

<%= ContactDescribe.where(["contact_describe_id = ?", "12"]).limit(1).pluck(:borrower_or_lender_text)  %> 

The field is retrieved successfully. But returns an array element. I need to learn how to convert that element to a string.

3

There are 3 best solutions below

0
On

The issue here is that where returns a collection - something similar to an array, just in ActiveRecord - no matter what limit you set on it. To retrieve the information you would use .first or [0] since you always only return one object.

But, since you are looking for a specific ContactDescribe object. Do this instead:

ContactDescribe.find_by(contact_describe_id: 12).borrower_or_lender

Additionally there two things you should improve in your code.

1: Logic should go into the controller or the model. A view is solely here to show objects.

2: What is up with the contact_describe_id field? Why not call it id. It seems redundant. Isn't user.id more convenient than user.user_id?

6
On

You can make use of join

<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).join(',')  %>
2
On

In addition to Deepak's answer, you can also convert the Array into a "Sentence" String

<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).to_sentence %>

Recommendation:

  • As pointed out by TheChamp, it is best practice to already "prepare" the values needed in the views as instance variables from the controller. See my recommended refactor

    # controller
    def YOUR_ACTION_NAME
      @contact_describe = ContactDescribe.where(contact_describe_id: 12).first
    end
    
    # view
    <%= @contact_describe.borrower_or_lender_text %>
    

Note: you won't even need pluck anymore unless you have other reasons why you want limit(1)