Error in displaying data in Rails

I am trying to display data in the view for a member’s profile. When I run the inspect option on the variable, it prints out all of the data on the profile variable. But, when I have it only call a column, I get an error.

I run the same code on a different variable and it prints out; so, I am a bit confused on what is going on. Is it because the Active Record has a relation? Here is the code:

profiles_controller.rb

def show
  @show_page = params[:id]
  @member = current_member
  @profile = Profile.where(member_id: current_member.id)    
end

show.html.erb

<hr>
<%= @show_page.inspect %>
<hr>
<%= @profile.inspect %>
<hr>
<%= @member.inspect %>
<hr>

<p>
  <strong>Member ID:</strong>
  <%= @member.id %>
</p>

View in Browser

"8"

#<ActiveRecord::Relation [#<Profile id: 6, f_name: "Test", l_name: "Member", u_name: "testing", security: "10", private: "1", avatar: nil, birthday: nil, phone: nil, address1: nil, address2: nil, city: nil, state: nil, zip: nil, long: nil, lat: nil, facebook: nil, twitter: nil, instagram: nil, pinterest: nil, googleplus: nil, motto: nil, created_at: "2017-12-23 05:15:53", updated_at: "2017-12-23 05:15:53", member_id: 8>]>

#<Member id: 8, email: "[email protected]", created_at: "2017-12-19 20:02:34", updated_at: "2017-12-23 05:15:37">

Member ID: 8

Now, when I add the following code into the show page, I get an error.

show.html.erb

<p>
  <strong>User Name:</strong>
  <%= @profile.u_name %>
</p>

ERROR

Showing /Users/topher/Dropbox/railsapps/~sandboxes/temporary/app/views/profiles/show.html.erb where line #21 raised:

undefined method `u_name' for #<Profile::ActiveRecord_Relation:0x00007fcb2583b920>
Did you mean?  name

I am just confused on if there is a different way that I need to be calling the data found in the variable. The only difference between the @member and @profile print outs that I can see is the #<ActiveRecord::Relation [ prefixed to @profile. Does this mean that I need to call the information differently?

Answer

#where is query method, and returns records matching query conditions wrapped in ActiveRecord::Relation object. Which explains why you are getting this error. To resolve it, you need to change it to:

@profile = Profile.where(member_id: current_member.id).first

Which will return first record matching given member id to @profile instead of ActiveRecord::Relation object.

However, you must use a finder method in case you want to find a particular record. So better and cleaner approach would be:

@profile = Profile.find_by(member_id: current_member.id)

Leave a Reply

Your email address will not be published. Required fields are marked *