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
. Then I have a model called Color
. In this DB table are stored all colors (red, blue, ...). And then there is the 4th model, called CarColor
. This model contains two columns - job_id
and 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.
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 ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.