【问题标题】:has_one association with user and customer and rails view formhas_one 与用户和客户的关联以及 Rails 视图表单
【发布时间】:2013-01-22 15:56:35
【问题描述】:

我有一个 has_one 关联:

has_one 关联用户 -> 客户模型

用户将拥有 customer_id 还是客户将拥有 user_id 属性?

其他问题:在我的 _form 中,我想对所有未与客户关联的用户进行选择/选项,这是最好的方法吗?

非常感谢。

【问题讨论】:

    标签: ruby-on-rails view associations


    【解决方案1】:

    _id 字段始终在具有belongs_to 的模型中,并引用其他表名。

    class Customer < ActiveRecord::Base
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_one :customer
    end
    

    在这种情况下,customers 表将有一个 user_id 字段。

    对于第二个问题,使用外连接在 SQL 中找到缺失值。 你想要的 SQL 是

    select 
    from users
      left outer join customers on users.id = customers.user_id
    where customers.id is null
    

    在 ActiveRecord 中,为您的 User 类添加一个范围。

    在 Rails 3.x 中:

    class User < ActiveRecord::Base
      has_one :customer
    
      scope :missing_customer,
        includes(:customer).where("customers.id is null")
    end
    

    在 Rails 2.3.x 中:

    class User < ActiveRecord::Base
      named_scope :missing_customer,
        { :joins => "left outer join customers on users.id = customers.user_id",
          :conditions => "customers.id is null" }
    end
    

    【讨论】:

    • 好的,谢谢,也许范围是相反的,我需要在我的客户表单视图中缺少用户,并且选择选项标签显示所有不在 user_id 字段中的客户表中的用户
    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多