0

我已经使用 Devise gem 设置了一个应用程序来登录(用户模型)。在注册视图中,我包含了一个 simple_fields_for 表单,其中包含来自 Student 模型的属性。

一切都在视图中正确显示,但是当单击提交按钮时,不会创建嵌套记录。

用户模型

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :role,    :student_attributes
# attr_accessible :title, :body

has_one :student, :inverse_of => :user, :autosave => true
accepts_nested_attributes_for :student

end

学生模型

Class Student < ActiveRecord::Base
  attr_accessible :course, :email, :fname, :lname, :student_num, :university, :year

  set_primary_key :student_num

  belongs_to :user, :inverse_of => :student, :autosave => true

  has_many :attendances
  has_many :teaching_sessions, through: :attendances

  has_many :completed_outcomes

  validates :student_num, presence: true
  validates :fname, presence: true
  validates :lname, presence: true
  validates :university, presence: true
  validates :course, presence: true
  validates :year, presence: true
  validates :email, presence: true


  def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
    Student.create! row.to_hash
end
  end

  def full_name
    "#{fname} #{lname}"
  end

end

设计登记表

<h2>Sign up</h2>

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>

<h3>Login Details</h3>

<div class="form-inputs">

  <%= f.input :email, :required => true, :autofocus => true %>
  <%= f.input :password, :required => true %>
  <%= f.input :password_confirmation, :required => true %>
  <%= f.select :role, ["Student","Teacher","Admin"], :required => true %>
</div>

<h3>Profile</h3>

<div id = "student_fields">
  <%= simple_fields_for :student do |s| %>
    <%= s.input :student_num %>
    <%= s.input :fname %>
    <%= s.input :lname %>
    <%= s.input :university %>
    <%= s.input :course %>
    <%= s.input :year %>
  <% end %>
</div>

<br />

<div class="form-actions">
  <%= f.button :submit, "Sign up" %>
</div>

<% end %>

<br />

<%= render "devise/shared/links" %>

定制设计控制器

class Users::RegistrationsController < Devise::RegistrationsController

  def new
    resource = build_resource({})
    resource.build_student
    respond_with resource
  end

  def create
super
  end

  def update
super
  end

end

我已经阅读了这里的几乎所有帖子,但仍然找不到在单击提交按钮时保存嵌套模型的方法。用户记录创建没有问题,但学生详细信息不保存。如果有人有任何建议,我将不胜感激。我确定这是我想念的非常简单的事情,但我整天都在为此苦苦挣扎!

最好的祝愿,

麦克风

4

1 回答 1

0

你试过用“f”吗?在您的 simple_fields_for 的前面?

<%= f.simple_fields_for :student do |s| %>

请参阅:https ://github.com/plataformatec/simple_form#simple-fields-for

于 2013-10-07T02:19:28.573 回答