Ruby on rails RubyonRails-连接两个表
我有以下资料: 模式Ruby on rails RubyonRails-连接两个表,ruby-on-rails,Ruby On Rails,我有以下资料: 模式 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 "wid
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
我想连接这两个表,以便在视图中包含供应商的名称。控制器的正确语法是什么?首先,您的语法在造型模型中有点不正确。它应该是
供应商
单数
class Moulding < ActiveRecord::Base
# Set up associations
belongs_to :supplier
end
另外,如果你要在一堆模塑件中循环,你需要在初始查询中包含供应商,这样它就不会在每次列出供应商名称时都运行查询。其语法是:
@moulding = Moulding.find(params[:id],:include => :supplier)
我还建议看一下官方的活动记录和指南(适用于Rails 3)首先,您的造型模型中的语法有点不正确。它应该是
供应商
单数
class Moulding < ActiveRecord::Base
# Set up associations
belongs_to :supplier
end
另外,如果你要在一堆模塑件中循环,你需要在初始查询中包含供应商,这样它就不会在每次列出供应商名称时都运行查询。其语法是:
@moulding = Moulding.find(params[:id],:include => :supplier)
我还建议您从更广泛的角度查看官方的活动记录和指南(适用于Rails 3),您可以在ActiveRecord语句中使用:joins或:include。主要区别在于联接将进行内部联接,而include将进行外部联接 从广泛的角度来看,您可以在ActiveRecord语句中使用:joins或:include。主要区别在于联接将进行内部联接,而include将进行外部联接 您可能想在标签之外提及Ruby。标题和正文可能很有用。您可能希望在标签之外的地方提到Ruby。标题和正文可能很有用。@最新鲜的是,你可以从guides.rubyonrails.org中获得一些用处。特别是查看active record查询界面、布局和渲染以及action controller概述部分。dub非常感谢您的帮助。如果我在控制器中使用molding.find(params[:id],:include=>:supplier),我在视图中使用什么语法来引用供应商名称?该语法与我上面发布的语法相同。唯一不同的是,如果你说想要获得1000个模塑件的供应商名称,这将是一个显著的性能提升。@最新鲜的是,你可以从guides.rubyonrails.org中获得一些使用。特别是查看active record查询界面、布局和渲染以及action controller概述部分。dub非常感谢您的帮助。如果我在控制器中使用molding.find(params[:id],:include=>:supplier),我在视图中使用什么语法来引用供应商名称?该语法与我上面发布的语法相同。唯一不同的是,如果你想得到1000个模塑件的供应商名称,这将是一个显著的性能提升。