[英]Ruby on Rails - Join Two Tables
我有以下内容:
架构
create_table "mouldings", :force => true do |t|
t.string "suppliers_code"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.integer "supplier_id"
t.decimal "length"
t.decimal "cost"
t.decimal "width"
t.decimal "depth"
end
create_table "suppliers", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
楷模
class Moulding < ActiveRecord::Base
# Set up associations
belongs_to :suppliers
end
class Supplier < ActiveRecord::Base
# Associations
has_many :mouldings, :dependent => :destroy
end
调节器
def show
@moulding = Moulding.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @moulding }
end
end
我想加入两个表,以便可以在视图中包括供应商的名称。 控制器的正确语法是什么?
首先,您的语法在您的造型模型中有点偏离。 应该是supplier
单数
class Moulding < ActiveRecord::Base
# Set up associations
belongs_to :supplier
end
如果需要供应商名称,请在控制器或视图中使用它。
@moulding.supplier.name
同样,如果您要遍历一堆成型件,则需要在初始查询中包括供应商,这样它就不会在每次列出供应商名称时都运行查询。 其语法为:
@moulding = Moulding.find(params[:id],:include => :supplier)
我还建议您查看官方的Active Record Associations和Query Interface指南(适用于Rails 3)
从广义上讲,您可以在ActiveRecord语句中使用:joins或:include。 主要区别在于联接将执行内部联接,而包含将执行外部联接。 http://asciicasts.com/episodes/181-include-vs-joins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.