某些字段表City
create_table "cities", force: :cascade do |t|
t.string "name"
某些字段表顺序
create_table "orders", force: :cascade do |t|
t.integer "count"
t.integer "first_city_id"
t.integer "last_city_id"
模型订单
class Order < ActiveRecord::Base
belongs_to :city, inverse_of: :city
end
模型城市
class City < ActiveRecord::Base
has_many :orders, inverse_of: :order
end
来自Order in view
的工作输出数据<% @order.each do |orders| %>
<p> <%= orders.count %> </p>
<% end %>
控制器中的方法
def edit
@orders= Order.all
@order=Order.where(:user_id == current_user)
end
如果Order表中的first_city_id或last_city_id包含City Table的id必需条目,如何从名称Sity表中获取值?
答案 0 :(得分:0)
您应按如下方式设置订单关联:
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
从订单中获取第一个/最后一个城市名称变得简单:
@order = Order.first
@order.first_city.name
@order.last_city.name
如果您想从订单列表中获取第一个/最后一个城市名称,则应使用includes
或joins
来避免n + 1查询:
@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 %>
或
@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 %>
您可以从这两个文档获得更多信息和帮助&#34; RailsGuides - Active Record Associations&#34;和&#34; RailsGuides - Active Record Query Interface&#34;。