这是我的结构:
class Student
has_many :fruits, through: :students_fruits
end
class Fruit
has_many :students, through: :students_fruits
end
class StudentFruit
belongs_to :student
belongs_to :fruit
end
create_table "students_fruits", force: :cascade do |t|
t.integer "student_id"
t.integer "fruit_id"
t.boolean "own"
end
当我创建Student实例时,我可以选择水果。
但是,如何选择水果并同时输入own
字段?
例如:
Fruits Own
☑apple ☑
☑pear □
☑orange ☑
这是我当前的观点,我想将own
字段添加到表单中:
= simple_form_for(@student) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.association :fruits, as: :check_boxes
.form-actions
= f.button :submit
答案 0 :(得分:0)
两种方法:
class Person < ActiveRecord::Base has_many :addresses accepts_nested_attributes_for :addresses, allow_destroy: true end
class Person < ActiveRecord::Base has_many :addresses def address=(*args) # update address data to addresses table. end end
答案 1 :(得分:0)
您需要fields_for
使用accepts_nested_attributes_for
:
#app/models/student.rb
class Student < ActiveRecord::Base
has_many :student_fruits
has_many :fruits, through: :student_fruits
accepts_nested_attributes_for :student_fruits
end
#app/controllers/students_controller.rb
class StudentsController < ApplicationController
def new
@student = Student.new
@fruits = Fruit.all
@fruits.each { @student.student_fruits.build }
end
private
def student_fruits_fields
params.permit(:student).permit(student_fields_attributes: [:fruit_id, :own])
end
end
这样您就可以使用fields_for
:
#app/views/students/new.html.erb
<%= simple_form_for @student do |f| %>
<%= f.simple_fields_for :student_fruits, @fruits do |sf| %>
<%= sf.input :fruit_id, as: :check_box #-> this needs fixing %>
<%= sf.input :own, as: :boolean %>
<% end %>
<% end %>