Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Help with Model Association in Rails 4.0.2

I'm using rails 4.0.2 and trying to get through the treebook application.

I'm at the point where you have the Status and User model. In the tutorial they create an association between the models. I created the association however I did not put in the attr_accessible method because rails 4.0.2 uses strong parameters.

class Status < ActiveRecord::Base
    belongs_to :user

Once the association is created they are able to query the user_name with the following code in their view.


This does not seem to work for me. In the video it explains that the belongs_to association should allow for that in the view. My question is what am I missing. I wrote a method in the status controller to define @status.user but that doesn't seem right and the method I wrote only fires when I run "Show" not the "index" page.

So what is the best way to be able to call


Controller Code

class StatusesController < ApplicationController

  before_action :set_status,:set_user, only: [:show, :edit, :update, :destroy]

  # GET /statuses
  # GET /statuses.json

 def index
    @statuses = Status.all

  # GET /statuses/1
  # GET /statuses/1.json

  def show
    puts "debug msg #{@status.inspect}"

  # GET /statuses/new
  def new
    @status = Status.new

  # GET /statuses/1/edit
  def edit

  # POST /statuses
  # POST /statuses.json


    # Use callbacks to share common setup or constraints between actions.
    def set_status
      @status = Status.find(params[:id])
      puts "in set status"

    def set_user
      @status.user = User.find_by(@status.user_id)

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

3 Answers

I figured out the code was correct and I just had a data issues. I reset the database and the code is working.

Robert Goddard
Robert Goddard
15,019 Points

How were you able to get around the attr_accessible stuff on the User model? There is no user controller in which to do strong attributes.


Check out my post on stackoverflow. The code in that post works. The issue I had was my status.user_id did not match any user ids in the database. Take a look at your database tables and make sure the IDs match.