简体   繁体   English

如何在Rails中建模以下内容?

[英]How to model the following in rails?

I am using Rails 3.2.8 and mySql as the db. 我正在使用Rails 3.2.8和mySql作为数据库。 I have two models, Setup and Regions. 我有两个模型,安装程序和区域。 I can have only N regions (N right now being 6) and there can be many setups of which each setup has to be in one Region. 我只能有N个区域(N个现在是6个),并且可以有许多设置,每个设置必须位于一个Region中。

The most obvious way seems to be Setup has_one Region. 最明显的方法似乎是安装has_one Region。 However this gives every new setup a new region object. 但是,这为每个新设置提供了一个新的区域对象。 However, I wish to reuse the region object in a setup (so that when its parameters change, they change across the board for all setups) and not create a new Region for every setup I have. 但是,我希望在设置中重用region对象(以便当其参数更改时,它们在所有设置中都会改变),而不是为我拥有的每个设置都创建一个新的Region。 I am thinking the best way is the following 我认为最好的方法是以下

class Setup < ActiveRecord::Base
    attr_accessible :name, :region_id
end

class Region < ActiveRecord::Base
    attr_accessible :name
end

If I want the region associated with the setup in the controller I do 如果我想要与控制器中的设置相关联的区域,请执行

setup = Setup.find(id)
region = Region.find(setup.region_id)

I am just wondering aloud whether this is the way it is done or is there any other way to capture this in Rails with ActiveRecord or is there any neat abstraction around it so that i can do something like the following? 我只是大声地想知道这是否是完成的方式,或者是否有其他方法可以通过ActiveRecord在Rails中捕获它,或者周围是否有任何简洁的抽象,以便我可以执行以下操作?

region = setup.region

You probably want to do things the opposite to your first inclination -- Region has_many :setups , and Setup belongs_to :region (which would require Setup having a :region_id column, as you were thinking). 您可能想做与您的第一个倾向相反的事情Region has_many :setupsSetup belongs_to :region (按照您的想法,这将要求Setup具有:region_id列)。 Then, through the magic of Rails associations, Rails will give provide a number of association methods linking the two objects, such as: 然后,通过神奇的Rails关联,Rails将提供提供许多链接两个对象的关联方法,例如:

@setup.region # the region associated with that setup
@region.setups # all setups associated with the region

There are a bunch of association methods -- I'd recommend reading the Association Basics guid to familiarize yourself with them, particular the references for the has_many and belongs_to associations. 有很多关联方法-我建议阅读Association Basics指南以熟悉它们,尤其是has_manybelongs_to关联的引用。

use association in Setup model use belongs_to :region and Region model has_many :setups 在安装程序模型中使用关联使用belongs_to :region和区域模型has_many :setups

Like below:-- 如下所示:-

class Setup < ActiveRecord::Base
  attr_accessible :name
  belongs_to :region
end

class Region < ActiveRecord::Base
  attr_accessible :name
  has_many :setups
end

Then you can do 那你可以做
setup = Setup.find(id)
region = setup.region

听起来您的安装程序belongs_to一个Region。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM