Accessing the attribute of a related model in Rails

So, sorry if this does not occur coherently ... I don't know all my Ruby / Rails terminology (yet).

I have a model called "Profile" and a model called "User" and they are connected as follows:

class Profile < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_one :profile

Now, in the index and show views of the profiles that I created, I want to have access to the name attribute from the user model. How can i do this? I assume that I will need something in the controller that looks like this:

class ProfilesController < ApplicationController
  def show
    @user = User.find(params[:user_id])

And then enter it in the form as follows:

<%= @user.name %>

But this bit of code doesn't work right there.

Thanks for the help.

+3
source share
2 answers

name , :

<%= @user.profile.name %>

name , , rake db:migrate, , ; rails console ruby script/console, , :

> u = User.first
> u.name

, . NoMethodError: undefined method, , , name, , .

+4

. .

user_id?

, user_id Profile profile_id User?

0

Source: https://habr.com/ru/post/1788729/


All Articles