我计划将来制作基因型计算器。我打算让这个计算器最终能够从配对计算以下内容:列出所有可能性的颜色概率,基因型。
我想在一个非常简单的网页上创建一个下拉菜单/文本字段组合,以了解它是如何工作的,这样我就可以继续我的项目,并希望能够实现这一目标。我已经搜索并尝试解决这个问题,但我很遗憾。目前在我的数据库中,我有一个名为“colors”的表,其中包含以下模式:
id
angora_color
genotype
created_at
updated_at
我不打算让用户能够向此表单添加数据。我希望他们能够从下拉框中选择一种颜色,并在其下方的文本字段中获取基因型。
到目前为止我的代码如下:
class Color < ActiveRecord::Base
has_one :genotype
end
class Genotype < ActiveRecord::Base
has_one :color
end
index.html.erb:
<h2>Placeholder for Genotype List..</h2>
class PagesController < ApplicationController
def index
end
end
我感谢任何帮助。
答案 0 :(得分:0)
您确定只需要has_one关系吗?基因型不是很多颜色吗?和颜色可以是许多基因型的一部分?
你也不能让两个模型声明has_one。一个模型必须属于另一个模型。 belongs_to
应将外键设为<model_name>_id
的那个,例如genotype_id
。 genotype
。在您的表格中,您只放_id
。 Rails查找rails g model GenotypesColor genotype_id:integer color_id:integer
。
这里可能更好的是使用has_many through。创建连接模型,例如genotypes_colors:
class Genotype < ActiveRecord::Base
has_many :genotypes_colors
has_many :colors, through: :genotypes_colors
end
class GenotypesColor < ActiveRecord::Base
belongs_to :genotype
belongs_to :color
end
class Color < ActiveRecord::Base
has_many :genotypes_colors
has_many :genotypes, through: :genotypes_colors
end
然后将代码更改为:
{{1}}
现在您可以正确地将基因型与其颜色相关联。您可以在任一模型的表单中使用fields_for来创建将基因型与任何颜色相关联的基因型_颜色关联,反之亦然。如果这听起来是对的,请告诉我,我可以进一步帮助如何填写表格。
答案 1 :(得分:0)
现在我的迁移内容如下:
class CreateColors < ActiveRecord::Migration
def change
create_table :colors do |t|
t.string :angora_color
t.string :genotype
t.timestamps
end
end
end