Rails joker has_one username,dance has_one username

时间:2012-10-30 21:12:21

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2

在我的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

2 个答案:

答案 0 :(得分:1)

问题在于,当Rails期望它是username类的实例时,您将Username作为文本字段传递。我要做的不是让Username模型对DancerJoker模型进行验证,而是检查另一个模型是否存在冲突的用户名。这很简单:

 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模型和相关表,并向usernamedancers添加jokers字符串字段,并在模型中进行此验证。

答案 1 :(得分:0)

我通过将应用程序切换到mongodb来解决了这个问题。