Ray
Ray

Reputation: 9684

Undefined method rails 4

Why am I getting an undefined method error whenever I use this block of code:

<%= @user_infos.website %>

But works when I use the each loop?

<% @user_infos.each do |user| %>
   <%= user.website %>
<% end %>

UserInfos controller:

class UserInfosController < ApplicationController
  before_action :set_user_info, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @user_infos = UserInfo.all
    respond_with(@user_infos)
  end

  def show
    respond_with(@user_info)
  end

  def new
    @user_info = current_user.user_infos.build
    redirect_to :back
  end

  def edit
  end

  def create
    @user_info = current_user.user_infos.build(user_info_params)
    @user_info.save
    redirect_to :back
  end

  def update
    @user_info.update(user_info_params)
    respond_with(@user_info)
  end

  def destroy
    @user_info.destroy
    respond_with(@user_info)
  end

  private
    def set_user_info
      @user_info = UserInfo.find(params[:id])
    end

    def user_info_params
      params.require(:user_info).permit(:website, :location)
    end
end

Home controller:

class HomeController < ApplicationController
  def index
    @questions = Question.all.order("created_at desc")
  end

  def profile
    @user = User.find(params[:id])
    @answer = Answer.all.order("created_at")
    @questions = Question.all.order("created_at")
    @user_info = UserInfo.new
    @user_infos = UserInfo.all.order("created_at desc")
  end
end

My intentions is not to loop but just simply display the uer's information inside the profile view. Looping is causing double paragraphs and that is surely not how I want it.

Upvotes: 1

Views: 41

Answers (2)

MilesStanfield
MilesStanfield

Reputation: 4649

@user_infos = UserInfo.all.order("created_at desc")

gives you all UserInfo's so you can't use

<%= @user_infos.website %>

and if you are opposed to writing a loop yourself you can just use map to get all the websites in an array

<%= @user_infos.map(&:website) %>

Upvotes: 0

Pavan
Pavan

Reputation: 33542

@user_infos is a collection of records, not a single record. So you just can't use <%= @user_infos.website %> which gives you undefined method error.

Upvotes: 1

Related Questions