Displaying info contained in a tablet it "belongs to" and putting it in a view loop

49 Views Asked by At

I've searched for this answer and can't find it anywhere in stack overflow.

Here's my problem.

A gurgle belongs to user. A user has many gurgles

I want to be able to display in a loop, the data from another table that it has a active record relation to.

When I display gurgles own index.html.erb in a loop retrieving only its own table info, it works fine.

But when I try to retrieve the info of the user of which that gurgle belongs to, it throws an error.

There is something here I am just not getting and I am hoping someone can help. I get a lot of different errors depending how I change it but as it stands this is the error Im getting now...

It currently doesn't like @user.email...

NoMethodError in Gurgles # index undefined method `email' for # User::ActiveRecord_Relation Extracted source (around line #17):

      <tr>
        <td><p><%= image_tag("zombie_profile.png", width: '100px') %><%= gurgle.status %></p></td>
        <td><p><%= @user.email %></p></td>
      </tr>
    </tbody>
</table>

Here is my code:

My gurgle model file...

class Gurgle < ApplicationRecord
  belongs_to :user, foreign_key: "user_id"


end

My model for user (using devise engine here)...

class User < ApplicationRecord

  has_many :gurgles
  has_one :profile

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

My gurgle controller code...

class GurglesController < ApplicationController
  before_action :set_gurgle, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  layout 'gurgle'

  # GET /gurgles
  # GET /gurgles.json
  def index
    @gurgle = Gurgle.all


    @user = User.all

  end

  # GET /gurgles/1
  # GET /gurgles/1.json
  def show
  end

  # GET /gurgles/new
  def new
    @gurgle = Gurgle.new
  end

  # GET /gurgles/1/edit
  def edit
  end

  # POST /gurgles
  # POST /gurgles.json
  def create


    @user = User.find(current_user)
    @gurgle = @user.gurgles.new(gurgle_params)


    respond_to do |format|
      if @gurgle.save
        format.html { redirect_to @gurgle, notice: 'Gurgle was successfully created.' }
        format.json { render :show, status: :created, location: @gurgle }
      else
        format.html { render :new }
        format.json { render json: @gurgle.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /gurgles/1
  # PATCH/PUT /gurgles/1.json
  def update
    respond_to do |format|
      if @gurgle.update(gurgle_params)
        format.html { redirect_to @gurgle, notice: 'Gurgle was successfully updated.' }
        format.json { render :show, status: :ok, location: @gurgle }
      else
        format.html { render :edit }
        format.json { render json: @gurgle.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /gurgles/1
  # DELETE /gurgles/1.json
  def destroy
    @gurgle.destroy
    respond_to do |format|
      format.html { redirect_to gurgles_url, notice: 'Gurgle was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_gurgle
      @gurgle = Gurgle.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def gurgle_params
      params.require(:gurgle).permit(:status, :user_id)
    end
end

My gurgle index.html.erb code....

<p id="notice"><%= notice %></p>

<br />
<hr>

<table>
  <thead>
    <tr>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @gurgle.each do |gurgle| %>
      <tr>
        <td><p><%= image_tag("zombie_profile.png", width: '100px') %><%= gurgle.status %></p></td>
        <td><p><%= @user.email %></p></td>
      </tr>
    </tbody>
</table>

<br />

<p><%= link_to 'Edit', edit_gurgle_path(gurgle), class: "gurgle-links" %> | <%= link_to 'Delete', gurgle, method: :delete, data: { confirm: 'Are you sure?' }, class: "gurgle-links" %></p>

<br />
<hr>

    <% end %>


<br />
<br />

<%= button_to 'New Gurgle', new_gurgle_path, class: "btn btn-primary", method: :get %>

and finally the schema on how my tables are set up in the database....

ActiveRecord::Schema.define(version: 20170101132806) do

  create_table "gurgles", force: :cascade do |t|
    t.text     "status"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_gurgles_on_user_id"
  end

  create_table "profiles", force: :cascade do |t|
    t.string   "username"
    t.text     "about"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_profiles_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

What am I doing wrong or missing here....

2

There are 2 best solutions below

1
On BEST ANSWER
  def index
    @gurgle = Gurgle.all
  end

in index.html.erb try to update below code

<td><p><%= gurgle.user.email %></p></td>

with gurgle object you can access user email because you have association but sometimes it cause an error because your gurgle data does not contain user_id so it will throw an error

remove @user from index action

0
On

It should be:

<% @gurgle.each do |gurgle| %>
      <tr>
        <td><p><%= image_tag("zombie_profile.png", width: '100px') %><%= gurgle.status %></p></td>
        <td><p><%= gurgle.user.email rescue nil %></p></td>
      </tr>
<% end %>