City table fields

create_table "cities", force: :cascade do |t| t.string "name" 

Order table fields

 create_table "orders", force: :cascade do |t| t.integer "count" t.integer "first_city_id" 

Model Order

 class Order < ActiveRecord::Base belongs_to :city, inverse_of: :city end 

City model

 class City < ActiveRecord::Base has_many :orders, inverse_of: :order end 

Working data output from Order to view

 <% @order.each do |orders| %> <p> <%= orders.count %> </p> <% end %> 

Method in controller

 def edit @orders= Order.all @order=Order.where(:user_id == current_user) end 

How to get the name value from the Сity table, if the first_city_id in the Order table contains the id of the desired entry from the City table

  • Does your belongs_to :city work at all? city_id in this table, I do not see. - D-side
  • I wrote not a complete list of fields, is there first_city_id and last_city_id that store the id from the city table or does it necessarily require an explicit city_id and what if I need to save id in different fields twice? - fis
  • It is necessary to state the question in more detail and clearly. It is completely incomprehensible what is and what is needed. I would venture to suggest that you need something like City.find(order.first_city_id) - anoam
  • Try to write more detailed questions. Explain exactly what you see the problem, how to reproduce it, what you want to get as a result, etc. - Nicolas Chabanovsky
  • @NicolasChabanovsky The order table contains the first_city_id field, which stores the id of the city table. You need to access the fields of the city table with the specified id in first_city_id . - fis

1 answer 1

The correct answer to my question can be found in the English version: https://stackoverflow.com/questions/36614560/get-data-from-related-tables-rails?noredirect=1#comment60826048_36614560 by Sibevin Wang

You should setup the order associations as follows:

 class Order < ActiveRecord::Base belongs_to :first_city, class_name: "City" # it would use first_city_id as the foreign key by default to access city table belongs_to :last_city, class_name: "City" end 

Becoming easy:

 @order = Order.first @order.first_city.name @order.last_city.name 

If you want to get the order list, you can use it:

 @orders = Order.includes(:first_city, :last_city) <% @orders.each do |order| %> <p> First City: <%= order.first_city.name %> </p> <p> Last City: <%= order.last_city.name %> </p> <% end %> 

or

 @orders = Order. joins("LEFT JOIN cities AS first_cities ON first_cities.id = orders.first_city_id"). joins("LEFT JOIN cities AS last_cities ON last_cities.id = orders.last_city_id"). select("orders.*, first_cities.name AS first_city_name, last_cities.name AS last_city_name") <% @orders.each do |order| %> <p> First City: <%= order.first_city_name %> </p> <p> Last City: <%= order.last_city_name %> </p> <% end %> 
  • Not bad, it remains to translate :) - D-side