-1
class Student < ActiveRecord::Base
  attr_accessible :dob, :grade_status, :school_id

  belongs_to :school
end

class School < ActiveRecord::Base
  attr_accessible :location, :name

  has_many :students
end

class HomeController < ApplicationController
    def index
      @school = School.new
      @student = @school.students.build(params[:student])
      School.create(params[:school])
    end
end
4

3 に答える 3

1

accepts_nested_attributes_for :studentsSchool モデルに追加し:students_attributes、attr_accessibleに追加します

于 2013-06-15T19:39:54.493 に答える
0

あなたのparamsハッシュには、「学校」キーの中に「学生」キーが含まれているようです。これは正確ですか?次のようになります。

{ school: { name: 'Foo', location: 'Bar', students: [...] } }

これが事実であると仮定します。ネストされた属性を使用し、次を追加する必要があります。

accepts_nested_attributes_for :students

あなたの学校のモデルに。また、School モデルのラインに追加students_attributesしてください。attr_accessible

ビューでは、ヘルパーを使用して、Rails がパラメーターでキーをfields_for構築できるようにする必要があります。students_attributes次のようになります。

form_for @school do |f|
   f.text_field :name
   f.text_field :location
   f.fields_for :students do |builder|
     builder.text_field :dob
     ...

(これはすべてERB、Haml、または使用しているものにある必要があります)

ネストされたフォームの Railscast は次のとおりです: http://railscasts.com/episodes/196-nested-model-form-part-1まだ問題がある場合。

于 2013-06-15T19:43:56.547 に答える