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

Greg Schloemann
1,090 PointsHelp 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
end
Once the association is created they are able to query the user_name with the following code in their view.
<%=@status.user.first_name%>
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
<%=@status.user.first_name%>
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
end
# GET /statuses/1
# GET /statuses/1.json
def show
puts "debug msg #{@status.inspect}"
end
# GET /statuses/new
def new
@status = Status.new
end
# GET /statuses/1/edit
def edit
end
# POST /statuses
# POST /statuses.json
...
...
...
private
# Use callbacks to share common setup or constraints between actions.
def set_status
@status = Status.find(params[:id])
puts "in set status"
end
def set_user
@status.user = User.find_by(@status.user_id)
end
# Never trust parameters from the scary internet, only allow the white list through.
def status_params
params.require(:status).permit(:content, :user_id)
end
end
3 Answers

Greg Schloemann
1,090 PointsI figured out the code was correct and I just had a data issues. I reset the database and the code is working.

Robert Goddard
15,019 PointsHow 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.
Thanks

Greg Schloemann
1,090 PointsCheck 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.
http://stackoverflow.com/questions/21082712/displaying-associated-objects-in-rails-views