【问题标题】:Rails - Creating a notifications model for UsersRails - 为用户创建通知模型
【发布时间】:2010-12-07 20:39:39
【问题描述】:

我正在为应用中的用户创建通知模型。他们收到哪些电子邮件等。

我将创建一个模型 UserNotifications,每个设置都有一堆二进制列。

我还没有从 Rails 学到的是,每个用户都需要在 UserNotifications 模型中记录。那么我该怎么做:

  1. 创建用户后,在 UserNotifications 表中为该用户添加一条记录?
  2. 处理数据库中的所有现有用户。迁移时,如何告诉 Rails 为数据库中的所有用户用户构建 UserNotification 记录?

感谢您引导我完成这一切。我以前没有在 Rails 中创建过这样的模型。

【问题讨论】:

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


    【解决方案1】:

    这是你在 after_create 中所做的事情:

    class User < ActiveRecord::Base
    
      belongs_to :user_notification
      after_create :create_user_notification
    
    
      def create_user_notification
        #additional logic probably needed per app requirements
        user_notification.create
      end
    end
    

    在您的迁移中,您只需迭代现有用户并调用#create_user_notification

    【讨论】:

    • 在尝试迁移时,我得到“#<:connectionadapters::postgresqladapter:0x105edb948> 的未定义方法 `create_user_notification'”
    • belongs_to vs has_one:我假设 UserNotification 的外键在用户身上,回想起来这可能是一个无效的假设。如果外键在 UserNotification 上,它将是 has_one,在 UserNotification 上带有 belongs_to
    • 对于迁移,请编辑您的问题并添加迁移定义和模型定义的相关部分。
    猜你喜欢
    • 2012-07-16
    • 2015-08-06
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多