在我的rails应用程序中,我有一个用户名模型,它多态地附加到2个模特小丑和舞者。
创建Joker时,表单会发送一个字符串,该字符串是Joker的用户名。我应该如何设置它以便rails在接收字符串而不是AR对象时不会抛出错误,用户名?
这是我现在的代码。
class Joker < ActiveRecord::Base
attr_accessible :username
has_one :username
end
和创建Jokers_controller
@joker = Joker.new(params[:joker])
Rails抛出此错误:
Username(#19110) expected, got String(#9130)
所以这是表单字段
= form_for @joker do |f|
- if @joker.errors.any?
#error_explanation
h2 = "#{pluralize(@joker.errors.count, "error")} prohibited this joker from being saved:"
ul
- @joker.errors.full_messages.each do |message|
li = message
= f.text_field :username
答案 0 :(得分:1)
问题在于,当Rails期望它是username
类的实例时,您将Username
作为文本字段传递。我要做的不是让Username
模型对Dancer
和Joker
模型进行验证,而是检查另一个模型是否存在冲突的用户名。这很简单:
class Dancer < ActiveRecord::Base
validate :unique_username
# your model code goes here
private
def unique_username
if Joker.find_by_username(username)
errors.add(:username, "is already taken")
end
end
end
因此,请移除Username
模型和相关表,并向username
和dancers
添加jokers
字符串字段,并在模型中进行此验证。
答案 1 :(得分:0)
我通过将应用程序切换到mongodb来解决了这个问题。