Accessing an attribute of a linked model in Rails
So, sorry if this doesn't come across coherently... I don't know all my Ruby / Rails terminology (yet).
I have a model called "Profile" and a model called "User, and the two are linked like this:
class Profile < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_one :profile
Now, in the "index" and "show" views of profiles that I made, I want to be able to access the attribute "nam开发者_StackOverflow社区e" from the User model. How can I do this? I imagine I'll need something in the controller that looks like this:
class ProfilesController < ApplicationController
def show
@user = User.find(params[:user_id])
And then access it in the view like this:
<%= @user.name %>
But that bit of code right there doesn't work.
Thanks for the help.
If the attribute name
belongs to the Profile model, in your view:
<%= @user.profile.name %>
If the attribute name
belongs to the User model, please stop the server, run rake db:migrate
to be sure every migration has been applied to your database; then run rails console
or ruby script/console
to check if the attribe is working for your model:
> u = User.first
> u.name
If the last command returns an empty string or the name of your first user, everything is working. If you get a NoMethodError: undefined method
you should check your database as the column that should handle the name
attribute is probably missing.
Your controller should work. That part is correct.
a few questions
Does your profile have a user_id ?
Did you run a migration that created attributes user_id for Profile
and profile_id for User
?
精彩评论