Novice
Novice

Reputation: 443

How to display attributes of an associated model in a view?

I have two models. Users and Feedbacks

class User < ActiveRecord::Base
  has_one :feedback
  attr_accessible :email,user_role,.......
end 

class Feedback < ActiveRecord::Base
  belongs_to :user
  attr_accessible :suggest_status, :support_status, :goal_status, :problem, :suggestions
end

I'm trying to display all the feedbacks to admin .

My feedback controller looks like this

class FeedbacksController < ApplicationController
  def index
    @feedbacks = Feedback.all
  end 

  def new
    @feedback = Feedback.new
  end

  def create
    @user = current_user
    @feedback = Feedback.new(params[:feedback])
    @user.feedback = @feedback

    if @feedback.save 
      flash[:notice] = "feedback submitted successfully!"
      redirect_to @user
    else 
      flash.now[:warning] = "Error submitting feedback."
      render :new
    end
  end
end

Now I want to display email of user associated with each feedback. I'm able to display user_id but I'm not sure how to display email of user model.

My index.html.haml for feedbacks look like this

= stylesheet_link_tag 'all' 
%h1 All Feedbacks
%table#feedbacks
  %thead
    %tr
      %th Feedback Number
      %th Goals
      %th Suggest
      %th Support
      %th User ID

  %tbody
  - @feedbacks.each do |feedback| 
    %tr
      %td= feedback.id
      %td= feedback.goal_status
      %td= feedback.suggest_status
      %td= feedback.support_status
      %td= feedback.user_id

Upvotes: 2

Views: 46

Answers (1)

Ben Lee
Ben Lee

Reputation: 53309

The problem is that when creating the feedback, you need to assign the user to the feedback, because it's the feedback you'll be saving. As it is, you're doing it the other way, assigning the feedback to the user, but not saving the user. So instead of this:

@user.feedback = @feedback

Do this:

@feedback.user = @user

You may also want to consider adding a validation on the Feedback model to prohibit saving a feedback without a user, like this:

validates_presence_of :user

Once that's set up right, then your associations should work correctly. The belongs_to :user allows you to just reference the association directly, like this:

%td= feedback.user.email

Also, for efficiency's sake you should eager load the users when you load the feedbacks:

@feedbacks = Feedback.includes(:user).all

Doing this will just execute two queries -- one to get all the feedbacks and another to get all the users. If you don't eager load, then you will have a multitude of queries -- one to get all the feedbacks, but then many more queries, one for each user.

Upvotes: 2

Related Questions