【发布时间】:2015-02-28 14:44:40
【问题描述】:
我正在为一个项目在 ruby on rails 中构建教程应用程序,并且我正在尝试在两个模型之间创建关联。
在我的数据库中,有用户、事件和与来自用户的电子邮件和来自事件的代码相关联的出勤表。
我尝试自己研究如何执行此操作,但每次我尝试向用户验证出席电子邮件时,它都会指出该用户不能为空白,就像我正在尝试创建一个新用户一样。
对于 Ruby on Rails 来说还是很新的东西,所以任何建议都将不胜感激!型号如下。
用户模型:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
has_many :attendances, inverse_of: :user
accepts_nested_attributes_for :attendances
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates(:name, presence: true, length: { maximum: 50 })
validates(:email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false})
validates(:password, length: { minimum: 6 } )
validates(:password_confirmation, presence: true)
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
出勤模式:
class Attendance < ActiveRecord::Base
attr_accessible :code, :email
belongs_to :user
validates_presence_of :user
end
到目前为止,我只是在尝试强制用户和出勤之间的关联,一旦我得到这个工作,我将对事件做同样的事情。另外,这是 Rails 3.2.19 和 Ruby 1.9.3。
编辑:这是我用于表单的代码,我相信它可以工作,因为在我将验证放入模型之前,它会在出勤表中创建行。
<% provide(:title, 'Test Event') %>
<h1>Attendance Registration</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@attendance) do |f| %>
<%= render 'shared/attendance_error_messages' %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :code %>
<%= f.text_field :code %>
<%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
另外,这里是考勤控制器,如果有帮助的话。
class AttendancesController < ApplicationController
def new
@attendance = Attendance.new
end
def create
@attendance = Attendance.new(params[:attendance])
if @attendance.save
flash[:success] = "Attendance logged."
redirect_to root_path
else
render 'new'
end
end
end
【问题讨论】:
-
您能告诉我更多关于您何时收到此错误的信息吗?
-
我制作了一个页面,允许某人输入电子邮件和代码以在指定的出勤表中创建新行。但是,这样做时,我收到一个闪存错误,提示“* 用户不能为空白”。另外,我知道此页面可用于创建新的出勤行,因为直到我在出勤模型中进行验证之前,它才能正确创建该行。
-
在用户模型中定义了has_may与inverse_of的关系,尝试在出勤模型中也指定inverse_of,belongs_to :user, :inverse_of :attendence
-
不幸的是,它似乎仍然有同样的问题,说明用户不能为空。
-
粘贴表单代码
标签: ruby-on-rails ruby ruby-on-rails-3 associations