开发者

how to bind association in RoR

开发者 https://www.devze.com 2023-01-02 22:48 出处:网络
I have two tables, AppTemplate and AppTemplateMeta AppTemplate table has column id, MetaID, name etc. I have associated these two model like this

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

精彩评论

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

关注公众号