【问题标题】:How to build a unique database model Ruby on Rails 4如何构建独特的数据库模型 Rub​​y on Rails 4
【发布时间】:2015-01-13 05:01:20
【问题描述】:

我目前有三种模型:两种支持 Devise auth gem 的不同用户模型:社区组织者和普通用户,以及一种社区活动模型。

我正在尝试让社区组织者创建活动:

  • 用户可以向哪些人捐款;
  • 哪些用户可以参加。

我使用 Stripe 作为支付网关。到目前为止,我已经为 Event 模型设置了一个控制器/模型脚手架:

class Event < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged
  belongs_to :org_user #organization_user
  has_one :category
end

这是我的组织用户模型:

class OrgUser < ActiveRecord::Base
  extend FriendlyId
  friendly_id :username, use: :slugged
  has_many :posts
  has_many :comments
  has_many :events
 end

有人告诉我,我的事件和 org_user 模型中可能需要这些特定模式

   class Event < ActiveRecord::Base
    event has_many :attendances
    event has_many :users, through: :attendances
   end

  class OrgUser < ActiveRecord::Base
    org_user has_many :attendances
    org_user has_many :events, through: :attendances
    end

class User < ActiveRecord::Base
end

您对建立这种关系有何建议。我也不想忘记 User.rb,它将签署表单以成为 :org_user 发布的事件的一部分。
只有 org_user 才能创建/发布事件。普通用户将有权访问注册表单以参加这些活动。请帮我清除这个障碍。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 devise


    【解决方案1】:

    几件事:

    • 你正确的方式有很多通过关系是错误的(见the doc
    • 您没有模拟从用户到事件的捐赠关系

    你可以这样建模:

      class Event < ActiveRecord::Base
        has_many :attendances
        has_many :users, through: :attendances
      end
    
      class OrgUser < ActiveRecord::Base
        has_many :events # as coordinations
      end
    
      class User < ActiveRecord::Base
        has_many :donations
        has_many :attendances
      end
    
      class Attendance < ActiveRecord::Base
        belongs_to :user
        has_one :event
      end
    
      class Donation < ActiveRecord::Base
        belongs_to :user
        has_one :event
      end
    

    【讨论】:

    • 我会在尝试过您的解决方案后向您报告。感谢您为我调查这个问题。
    • 关于出勤模型的快速问题 Pak。我应该创建一个新表来保存它的 id(多态)还是将其添加到当前模型中?你有什么建议。此外,在这种情况下,您将在模型旁边生成哪些属性:attendances user_id:integer event_id:integer 等,以便更好地描述。如果可以,请将其添加到您的原始答案中。我一看到解决方案就完成了。我会将其标记为已回答。
    • 是的,您需要创建新表。它更容易维护。 Rails 关联和迁移已经为您解决了这个问题,请参阅 rails 指南 :)
    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多