[英]Rails and has_many through association - how to properly set the form?
I am not sure I am setting my models correctly, so I would like to show you my idea: 我不确定我是否正确设置了模型,所以我想向您展示我的想法:
I have the model Car
that belongs to Company
. 我有属于Company
Car
模型。 Then I have a model called Color
. 然后,我有一个名为Color
的模型。 In this DB table are stored all colors (red, blue, ...). 在该数据库表中存储了所有颜色(红色,蓝色等)。 And then there is the 4th model, called CarColor
. 然后是第四个模型,称为CarColor
。 This model contains two columns - job_id
and color_id
. 这个模型包含两列- job_id
和color_id
。
In the view, I would like to allow visitors to pick out colours with using checkboxes. 在视图中,我希望允许访问者使用复选框来选择颜色。
= form_for @car do |f|
.field
= f.label :name
= f.text_field :name
.field
= f.label :location
= f.text_field :location
.field
= fields_for @car_colors do |cc|
...
.field
= fields_for @company do |c|
.field
= c.label :name
= c.text_field :name
.actions
= f.submit 'Save'
class Company < ActiveRecord::Base
has_many :cars
end
class Car < ActiveRecord::Base
belongs_to :company
has_many :car_colors
has_many :c_colors, :through => :car_colors
end
class Color < ActiveRecord::Base
has_many :car_colors
has_many :cars, :through => :car_colors
end
class CarColor < ActiveRecord::Base
belongs_to :car
belongs_to :color
end
Saving Cars
+ Company
works well, but I don't know how to add the checkboxes with colours in the view. Savings Cars
+ Company
运作良好,但我不知道如何在视图中添加带有颜色的复选框。
EDIT: Regarding to the thread in the comment, I made a progress. 编辑:关于注释中的线程,我取得了进展。 However, I found an error that I don't know how to solve. 但是,我发现了一个我不知道如何解决的错误。
I am using model structure shown above and this is how look like the view: 我正在使用上面显示的模型结构,这就是视图的样子:
- Color.order('name').each do |clr|
= check_box_tag :c_color_ids, clr.id, @car.car_colors.include?(clr), :name => 'car[c_color_ids][]'
= label_tag :c_color_ids, clr.name
This is the error I got: 这是我得到的错误:
PG::Error: ERROR: relation "car_colors" does not exist
What am I missing? 我想念什么? How the relation cannot exist? 关系如何不存在?
Ok, I spent a day of solving this issue. 好的,我花了一天的时间解决这个问题。 The scheme about is correct, the problem in my case was, that I have create a migration with table name car_color instead of car_colors ... 该方案是正确的,在我的情况下,问题是,我创建了一个迁移,其表名称为car_color而不是car_colors ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.