我以前遇到类似这个问题,但这次我无法解决它,我在这里做了很多搜索和谷歌,但我找不到我面临的相同情况
我有3个模特,学生,科目,参加,每次我尝试通过参加表格将学生分配给多个科目时,subject_id
保存为null
以防使用check_boxes
,我尝试使用f.association :subject
,但它给出了相同的结果,数组"attend"=>{"student_id"=>"1", "subject_id"=>["1", "2", ""]}}
中也有一个空值,这是我的代码
student.rb
class Student < ActiveRecord::Base
attr_accessible :first_name, :middle_name, :last_name, :gender, :user_id
belongs_to :user
has_many :attends
has_many :subjects, :through => :attends
def full_name
"#{self.first_name} #{self.last_name}"
end
end
subject.rb中
class Subject < ActiveRecord::Base
attr_accessible :subject_title, :subjectCode
has_many :attends
has_many :students, :through => :attends
end
attend.rb
class Attend < ActiveRecord::Base
attr_accessible :student_id, :subject_id
belongs_to :student
belongs_to :subject
end
出席/ new.html.erb
<%= simple_form_for(@attend) do |f| %>
<%= f.association :student, as: :select, label_method: :full_name, prompt: 'Select Student' %>
<%= f.input :subject_id, collection:@subjects, as: :check_boxes,label_method: :subject_title, value_method: :id %>
<% end %>
attends_controller.rb
class AttendsController < ApplicationController
def index
@attends = Attend.all
end
def show
@attend = Attend.find(params[:id])
end
def new
@attend = Attend.new
@subjects = Subject.all
end
def create
@attend = Attend.new(params[:attend])
if @attend.save
redirect_to attends_path
else
render 'new'
end
end
def edit
@attend = Attend.find(params[:id])
end
def update
@attend = Attend.find(params[:id])
if @attend.update_attributes(params[:attend])
redirect_to attends_path
else
render 'edit'
end
end
def destroy
@attend = Attend.find(params[:id])
end
end
服务器开发日志
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8Z9LTJbYpNnFtvLKs4MpO2pongrKmFkSIz0jzxcuQH0=", "attend"=>{"student_id"=>"1", "subject_id"=>["1", "2", ""]}}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "attends" ("created_at", "student_id", "subject_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sat, 14 Dec 2013 11:34:02 UTC +00:00], ["student_id", 1], ["subject_id", nil], ["updated_at", Sat, 14 Dec 2013 11:34:02 UTC +00:00]]
(169.6ms) commit transaction
答案 0 :(得分:0)
您正试图以简单的形式保存中间关系。在您的控制器创建方法中,@ attend仅用于保存一条记录。但是你想在那里输入很多科目。问题只出在那里。