Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I input join table field in a form in Rails

This is my structure:

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

When I create Student instance, I can select the fruits.

However, how to select the fruits and input the own field at the same time?

For example:

Fruits      Own

☑apple      ☑

☑pear       □

☑orange     ☑

This is my current view, I want to add the own field into the form:

= 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
like image 289
Stephen Avatar asked Nov 26 '25 22:11

Stephen


1 Answers

You'll need to use fields_for with 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

This will allow you to use 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 %>
like image 128
Richard Peck Avatar answered Nov 29 '25 14:11

Richard Peck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!