开发者

how to bind association in RoR

I have two tables, AppTemplate and AppTemplateMeta

AppTemplate table has column id, MetaID, name etc.

I have associated these two model like this

class AppTemplate < ActiveRecord::Base
  set_table_name 'AppTemplate'
  belongs_to :app_template_meta, :class_name开发者_C百科 => "AppTemplateMeta", :foreign_key => 'MetaID'
end

If we fetch data using AppTemplate.all, I want associated meta details also. But currently it's not returning associated meta details. It just returns AppTemplate details. any guys can help me for this


If I understood correctly, you want something like the following:

# models
class AppTemplate < ActiveRecord::Base
  # table names usually looks like this: app_template.
  # the same for columns names. so you should have 'meta_id' as foreign key
  set_table_name 'AppTemplate'
  belongs_to :app_template_meta, :class_name => "AppTemplateMeta",
     :foreign_key => 'MetaID'
end

class AppTemplateMeta < ActiveRecord::Base
  has_one :app_template # or has_many
end

# controller
# get all app templates and load the associated app_template_meta for each one
@app_templates = AppTemplate.all(:include => :app_template_meta)
# get associated app_template_meta for the first app_template
@app_templates.first.app_template_meta
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜