0

我想将一组值从一个关联模型放到另一个模型中。如果我的学生有一天到达,我正在制作一个注册网站。所以我有一个有很多“学生模型”的“日模型”。我希望我的同事能够检查在校的学生,并能够创建一个包含许多学生的日实例。

我可以获得多个参数,但我无法将多个 student_id 保存到日模型中。这就是我现在所拥有的。

日控制器

    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

日模型

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

学生模型

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

意见/天/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 %>

痕迹

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)
4

1 回答 1

0

问题出在数据库逻辑上。你需要有一个 has_many_through 关系才能工作。

试试这个指南http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

于 2013-04-13T09:01:24.157 回答