Lesly Revenge
Lesly Revenge

Reputation: 922

Getting error when calling db data from show view in Ruby on Rails

to easy answer that is pissing me off.

I'm getting this error: for undefined method `intro' for #

My Model:

about model

    belongs_to :user

User model

    has_many :abouts

user controller

   def show

       @user = User.find(params[:id])
       @about = @user.abouts

user show view

<div class="col-md-12">
<h2 class="page-header">Introduction</h2>

<p> <%= @about.intro %> <br></p>

Upvotes: 0

Views: 41

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

Each User has_many About objects, so @user.abouts will return an ActiveRecord::Relation object type. This object is not an About object – instead, it's a collection of About objects that can be iterated through to access each constituent member. Try the following:

# app/controllers/users_controller.rb
def show
    @user = User.find(params[:id])
    @abouts = @user.abouts
end

# app/views/users/show.html.erb
<% @abouts.each do |about| %>
    <p> <%= about.intro %> <br></p>
    <p> <%= about.cost %> <br></p>
<% end %>

EDIT:

If – as the OP is suggesting in the suggested edits – only a single About record should be returned from a User, then it's better to place this logic within the controller than in the view:

# app/controllers/users_controller.rb
def show
    @user = User.find(params[:id])
    @abouts = @user.abouts.first
end

# app/views/users/show.html.erb
<p> <%= @about.intro %> <br></p>
<p> <%= @about.cost %> <br></p>

Upvotes: 3

Related Questions