ActiveRecord - 如何知道另一个表中是否存在字段?

时间:2015-06-01 12:40:35

标签: ruby-on-rails ruby activerecord

如果具有相同邮件ID的用户已注册,我想将获胜者表中的status更新为trues。我坚持积极的记录。

schema.rb

   create_table "winners", force: :cascade do |t|
     t.string   "name"
     t.string   "email"
     t.string   "phonenumber"
     t.boolean  "status",      default: false
     t.datetime "created_at",                  null: false
     t.datetime "updated_at",                  null: false
   end

表2

   create_table "users", force: :cascade do |t|
     t.string   "email",                  default: "", null: false
     t.string   "encrypted_password",     default: "", null: false
     t.string   "nickname"
     t.string   "image"
     t.integer  "score",                  default: 0
   end

模型/ user.rb

    after_create :update_status
    def update_status
     #if self[:email] = #any mail in winners table
      #update the corresponding winners row with status.
     if Winners.where(email = :email)
     update attributes

    end

如何使用有效记录进行此类查询?

2 个答案:

答案 0 :(得分:1)

你可以试试这个,我希望这会对你有帮助。

model / user.rb

after_create :update_status

def update_status
  #update the corresponding winners row with status.
  winner = Winner.where("email = ?", self.email).first
  unless winner.blank
    winner.status = true  # Or false
    winner.save! # Or If You want to skip validation then use winner.save(validate: false)
  end
end

答案 1 :(得分:1)

如果你想在 model / user.rb中使用after_create挂钩:

 if (len(word)-1) < 1:
          word_real = word[randint(0, len(word)-1)]

您可能认为根据用户注册更新获奖者应该是控制器任务,而不是模型。我是在控制器中显式调用内容的朋友,而不是让它自动发生。这更具有个人品味,但这应该是完全没问题的。