0

I'm learning rails 4 and i'd like to know how to display in a show action an attribute coming from another model.

For information, a Deal belongs_to a business_line and a business_line has many deals.

Here is the show action for the deal controller. I'd like to display the name of the linked business_line (instead of the ID, which is stored in the Deal table) :

<div class = 'container'>
<h1> <%= @deal.name %> </h1>
<p> <%= @deal.bank_id %> </p>
<p> <%= business_line.name %> </p>

<%= link_to 'Home', root_path %>
<%= link_to 'Edit', edit_deal_path %>
<%= link_to 'Delete', deal_path(@deal), method: :delete, data: {confirm: 'Are you sure?'} %>
</div>

Here is my Deal controller :

class DealsController < ApplicationController
    before_action :find_deal, only: [:show, :edit, :update, :destroy]
def show
        @deal.business_line_id = @business_line.id
    end
private

    def deals_params
        params.require(:deal).permit(:name, :bank_id, :business_line_id)
    end

    def find_deal
        @deal = Deal.find(params[:id])
    end

end

What do i have to put into my Deal controller to be able to call the business_line.name in my Deal view?

Many thanks :)

1 Answer 1

2

You just need to call @deal.business_line.name since you already associated the models.

Just a question, why are you doing this in the show action? Where was @business_line initialized?

Sign up to request clarification or add additional context in comments.

2 Comments

@Etienne This will work as long as you have set up your Deal model and BusinessLine model with the has_many and belongs_to relationships that you referenced
Thank you very much! It worked :). By the way, if i wanted to be compliant with the law of Demeter, what would i need to do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.