Rob Matthews
Rob Matthews

Reputation: 161

displaying a model in a different model's view

I have two models so far in a rails application.

Within the applications view, I can display my User by inserting

<h1><%= @user.first_name %></h1>

But am not able to display

<h1><%= @wallet.money %></h1>

I get a no method error in users#show. I don't understand this error.

I have a method called show that contains @user = User.find(params[:id]) with params defined in a private method below.

My question is, do I need a controller and a view for my Wallet model? I didn't think I did because I am trying to display content through the applications controller. Even though the page being directed to is Users#show.

Ideally, since the wallet has a user_id, I'd love to display the money value through that... something like @user.wallet.money or something... to call the money value through the foreign key associated with the current user.

Upvotes: 0

Views: 62

Answers (1)

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

Probably, you have not defined @wallet, hence it is nil and hence the error, to use the association..

In your User model, you need to define the association as

has_one :wallet

In your wallet model..

belongs_to :user

Then controller

@user = User.includes(:wallet).find_by_id(params[:id])

Now in view, you can call it as

@user.wallet.money

I suggest you to go through association_basics to understand it better and help you in future..

Upvotes: 1

Related Questions