Ruby on rails 3 如何实现has_many:通过rails中的关系来实现这个示例
我一直在寻找类似的问题,但我仍然不知道如何实现这种关系。我当然有三个模型:Ruby on rails 3 如何实现has_many:通过rails中的关系来实现这个示例,ruby-on-rails-3,has-many-through,Ruby On Rails 3,Has Many Through,我一直在寻找类似的问题,但我仍然不知道如何实现这种关系。我当然有三个模型: class Recetum < ActiveRecord::Base attr_accessible :name, :desc, :duration, :prep, :photo, :topic_id has_many :manifests has_many :ingredients, :through => :manifests end class Ingredient <
class Recetum < ActiveRecord::Base
attr_accessible :name, :desc, :duration, :prep, :photo, :topic_id
has_many :manifests
has_many :ingredients, :through => :manifests
end
class Ingredient < ActiveRecord::Base
attr_accessible :kcal, :name, :use, :unity
has_many :manifests
has_many :recetum, :through => :manifests
end
class Manifest < ActiveRecord::Base
attr_accessible :ingredient_id, :quantity, :receta_id
belongs_to :recetum
accepts_nested_attributes_for :ingredient
belongs_to :ingredient
end
class Recetum:清单
结束
类组件:清单
结束
类清单
Recetum将是一个配方(脚手架时输入错误),此配方可能包含一个或多个成分(已在db上)。因此,当我创建一个新的容器时,我需要创建一个新的容器,并在清单中为用户输入的每个成分插入一条记录
我现在需要一些视图和控制器方面的帮助,如何创建包含成分字段的recetum表单,更重要的是,我需要修改recetum控制器的哪些内容
如果您有任何建议或帮助,我们将不胜感激,因为这一部分对我的项目至关重要,请提前感谢。您有两个选择,主要取决于您认为您想做什么。您想显示一组
max\u配料
还是完全动态显示?当然,对于用户来说,动态用例看起来更好,但它确实会产生一些更复杂的代码
下面是一个好的RailsCast,它解释了如何通过JavaScript动态执行此操作:
不幸的是,并不是每个人都运行了JavaScript,所以你可能想考虑静态的方式来做。
首先,我认为您不需要在清单
模型中为接受嵌套的属性。不过,我确实认为您的Recetum
模型中需要它。如果您选择的是静态路径,那么您可能还需要设置reject\u If
选项
accepts_nested_attributes_for :manifests, reject_if: :all_blank
完成此操作后,您需要将manifests\u属性添加到attr\u accessible
中
使用静态路由,您需要预构建一些清单
。在您的新
控制器中,您将需要如下内容:
max_ingredients.times do
@recetum.manifests.build
end
在编辑
和创建
和更新
的错误路径中,您可能需要:
(max_ingredients - @recetum.manifests.count).times do
@recetum.manifests.build
end
最后,您的视图需要某种方法来设置成分。我现在假设一个选择框
f.fields_for :manifests do |mf|
mf.label :ingredient_id, "Ingredient"
mf.collection_select :ingredient_id, Ingredient.all, :id, :name
您可能需要通过列表或表格添加某种格式
希望这足够让你开始了。太棒了,泰克人很多!还有一个问题,方法“build”到底做什么?build
有点像关联的new
。它接受属性散列并适当地设置外键id。