简体   繁体   English

Rails关联has_many通过代替HABTM

[英]Rails associations has_many through instead of HABTM

I'm fairly new to rails and ActiveRecord and I'm trying to find the correct way to model my data. 我对Rails和ActiveRecord还是相当陌生,我正在尝试寻找正确的数据建模方法。

I am building an application that let's swim instructors put together a class plan that shows what skills they will be teaching their class and what activities they will use to teach each skill. 我正在构建一个应用程序,让游泳教练可以制定一个班级计划,以显示他们将在课堂上教什么技能以及他们将用来教每种技能的活动。 A Plan can contain many Skills and each Skill can have many Activities associated with it. 一个计划可以包含许多技能,而每个技能可以具有许多与之相关的活动。

On the Plan form there is a widget for the skill-activity combination. 在“计划”表单上,有一个用于技能-活动组合的小部件。 In it, user should be able to select a Skill from a dropdown and for the selected skill select multiple activities from a list. 在其中,用户应该能够从下拉菜单中选择一项技能,并为所选择的技能从列表中选择多个活动。 This widget can repeat any number of times on the form. 此小部件可以在表单上重复任意次数。

My current model: 我当前的模型:

Class Plan
  has_many :plan_activities
end

Class PlanActivities
  belongs_to :plan
  belongs_to :skill
  has_and_belongs_to_many :activities
end

Class Skill
end

Class Activity
end

Is this model correct? 这个模型正确吗? My problem with it is that accepts_nested_attribtues_for does not work for HABTM associations. 我的问题是accepts_nested_attribtues_for对HABTM关联不起作用。 I've read that I can replace it with has_many through:, but that would mean adding yet another join model to the picture. 我读过可以通过has_many替换它:,但这意味着在图片中添加另一个连接模型。 It just seems a little too ugly. 看起来有点太难看了。 Is there a better way to do this? 有一个更好的方法吗?

EDIT: 编辑:

My Skills and Activities are in list form and I should be able to include the same skill and/or activity on multiple plans. 我的技能和活动是列表形式,我应该能够在多个计划中包含相同的技能和/或活动。

Your model is very close. 您的模型非常接近。 One improvement here would be to completely remove the PlanActivities model. 这里的一项改进是完全删除PlanActivities模型。 Just have the associations directly on the plan. 只需将协会直接纳入计划即可。 At this point I don't think the extra model is justified. 在这一点上,我认为额外的模型是没有道理的。 We have a pretty basic pyramid structure here. 我们这里有一个相当基本的金字塔结构。 At the top is plan with many skills, Each skill has many activities, so a simpler model would look like: 最上面是具有很多技能的计划,每个技能都有很多活动,因此一个简单的模型如下所示:

class Plan
  has_many :plan_skills
  has_many :activities, through: :plan_skills
end

class Skill
  has_many :activities, through: plan_skills
  has_many :plan_skills

end

class PlanSkill
  belongs_to :plan
  belongs_to :skill
  has_many :activities
end


class Activity
  belongs_to :plan_skill
end

The join model is an option but not entirely necessary here. 联接模型是一个选项,但在此并非完全必要。 Plan.activities will make the needed join table for you. Plan.activities将为您创建所需的联接表。

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

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