Question

I want to put an array of values from one associated model to another. I'm making a site that registers if my students has arrived one day. So I have a "day-model" that has many "students-model". I want my colleagues to be able to check the students thats in school and be able to create a day instance with many students.

I can get the multiple params but i cant save the multiple student_ids to the day model. This is what i have now.

Day-controller

    class DaysController < ApplicationController
    def new
        @days = Day.new
        @students = Student.all
    end
    def create
    @day = Day.new(params[:days])
    if @day.save
      redirect_to @day, :notice => "Successfully created student."
    else
      render :action => 'new'
    end
  end

  def show
    @day = Day.find(params[:id])

  end
end

day-model

class Day < ActiveRecord::Base
 attr_accessible :student_id
  has_many :students
end

Student-model

    class Student < ActiveRecord::Base
  attr_accessible :name, :group_id, :phone, :parentsphone
  validates :phone, :numericality => {:only_integer => true}
  belongs_to :days
end

views/day/new.html.erb

<%= simple_form_for @days do |f| %>
<%= f.collection_check_boxes :students,
                             Student.all,
                             :id,
                             :name,
                             :input_html => { :class => 'checkbox' },
                             :checked => @days.students %>


<%= f.submit "Skapa dag" %>
<% end %>

Trace

Started POST "/days" for 127.0.0.1 at 2013-04-12 22:52:11 +0200
Processing by DaysController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"yCwSiZCVR2Cy9qDMnQtPfQt9hysl975pqjW8nFPI828=", "day"=>{"students"=>["5", "14", "15", ""]}, "commit"=>"Skapa dag"}
   (0.1ms)  begin transaction
  SQL (18.3ms)  INSERT INTO "days" ("created_at", "student_id", "updated_at") VALUES (?, ?, ?)  [["created_at", Fri, 12 Apr 2013 20:52:11 UTC +00:00], ["student_id", nil], ["updated_at", Fri, 12 Apr 2013 20:52:11 UTC +00:00]]
   (1.3ms)  commit transaction
Redirected to http://localhost:3000/days/5
Completed 302 Found in 25ms (ActiveRecord: 19.7ms)
Was it helpful?

Solution

The problem is with the database logic. You need to have a has_many_through relationship for this to work.

Try this guide http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top