【问题标题】:Rails: belongs_to specific columnRails:belongs_to 特定列
【发布时间】:2014-01-06 09:56:22
【问题描述】:

我有以下型号:

class User < ActiveRecord::Base

  #method that I want to delete and replace with belongs_to
  def restaurant
      RemoteRestaurant.find_by_shortRD(self.INFO_SHORT_RD)
  end
end

在这种情况下我如何添加belongs_to :remote_restaurant?

【问题讨论】:

  • 你能试试belongs_to :remote_restaurant, foreign_key: 'shortRD'吗?我现在无法测试它,我不记得确切的语法。
  • INFO_SHORT_RD 常量是怎么回事?

标签: ruby-on-rails ruby orm model relation


【解决方案1】:
class User < ActiveRecord::Base
  belongs_to :restaurant, class_name: 'RemoteRestaurant', foreign_key: :shortRD, primary_key: :INFO_SHORT_KEY
end

【讨论】:

    【解决方案2】:

    使用您的自定义 foreign_key 和 primary_key 添加 belongs_to

    class User < ActiveRecord::Base
        belongs_to :remote_restaurant, :foreign_key => "INFO_SHORT_RD", :primary_key=>"shortRD"
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多