【问题标题】:Has-Many and Belongs-to-one Relation具有多和属于一的关系
【发布时间】:2013-02-13 00:06:07
【问题描述】:

我正在尝试跟踪用户创建的注册转化次数。
因此,我有以下两个模型:

signup_conversion.rb

class SignupConversion < ActiveRecord::Base
  belongs_to :user
  belongs_to :convertee, :class_name => "User", :foreign_key => 'convertee_id'
  attr_accessible :convertee_id
end

user.rb

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  belongs_to :signup_conversion
  has_many :signup_conversions
end

这样可以吗?还是我在这里遗漏了一些重要的东西?

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many


    【解决方案1】:

    我没有尝试过代码,但我给你一些提示,希望你觉得有用。

    • 我认为每个has_many/has_one 语句都应该有对应的belongs_to,所以三个belongs_to 和一个has_many 看起来不太好。

    • 我不确定has_one :signup_conversionhas_many :signup_conversions 是否能很好地搭配使用,所以我宁愿更改名称。我也更改了其他名称以尝试使关联更清晰,尽管我不确定我是否完全理解它们所代表的真实概念。你可能会想出更好的名字。

    • 默认情况下,外键猜测是在关联名称后面加上后缀_id,所以这种情况下不需要指定。另外,我认为您不需要使该属性可访问,至少不需要使关联起作用。

      signup_conversion.rb

      class SignupConversion < ActiveRecord::Base
        belongs_to :owner    , :class_name => "User"
        belongs_to :convertee, :class_name => "User"
      end
      

      user.rb

      class User < ActiveRecord::Base
        attr_accessible :name, :email, :password, :password_confirmation
        has_one  :owned_signup_conversion     , :class_name => "SignupConversion"
        has_many :triggered_signup_conversions, :class_name => "SignupConversion"
      end
      

    【讨论】:

    • 这就是我最终所做的 - 工作得非常好!感谢您将我推向正确的方向。
    【解决方案2】:

    这里的代码比你需要的多;你只需要

    class SignupConversion < ActiveRecord::Base
       belongs_to :user
    end
    
    class User < ActiveRecord::Base
       attr_accessible :name, :email, :password, :password_confirmation
       has_many :signup_conversions
    end
    

    然后您需要在您的 signup_conversions 表中添加一个 user_id 列,然后调用

    @user.signup_conversions
    

    在您的视图或控制器中。

    【讨论】:

    • 你没有得到问题:他需要用户和转换者关系......它就像一个帖子有很多评论者(用户对象)和一个作者(也是一个用户对象)
    • 是的,没错——这只是一个常规的 has_many 关系
    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    相关资源
    最近更新 更多