Ruby on rails Rails与多对多建立关系

Ruby on rails Rails与多对多建立关系,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我有两种型号: Property belongs_to :portfolios Portfolio has_many :properties 我需要投资组合中每个物业的安装成本记录。这些将与投资组合设置成本相关 如何设置这样的东西?这是一种多对多关系吗?最流行的是单传递关联,您可以这样做: class Property < ApplicationRecord has_many :property_portfolio_links has_many :portfolios, thr

我有两种型号:

Property
belongs_to :portfolios

Portfolio
has_many :properties
我需要投资组合中每个物业的安装成本记录。这些将与投资组合设置成本相关


如何设置这样的东西?这是一种多对多关系吗?

最流行的是
单传递关联
,您可以这样做:

class Property < ApplicationRecord
  has_many :property_portfolio_links
  has_many :portfolios, through: :property_portfolio_links
end

# in between
class PropertyPortfolioLink < ApplicationRecord
  belongs_to :property
  belongs_to :portfolio
end

class Portfolio < ApplicationRecord
  has_many :property_portfolio_links
  has_many :properties, through: :property_portfolio_links
end
total_setup_costs = @portfolio.setup_cost + @portfolio.properties.pluck(:setup_costs).inject(:+)
类属性
从您的问题和评论中,我了解到您希望投资组合和房地产的安装成本。你不需要多对多的关系。您可以在两个表(即财产和投资组合)中添加“设置成本”列

随后,如果您需要投资组合的总安装成本,包括其房地产的安装成本,您可以这样做:

class Property < ApplicationRecord
  has_many :property_portfolio_links
  has_many :portfolios, through: :property_portfolio_links
end

# in between
class PropertyPortfolioLink < ApplicationRecord
  belongs_to :property
  belongs_to :portfolio
end

class Portfolio < ApplicationRecord
  has_many :property_portfolio_links
  has_many :properties, through: :property_portfolio_links
end
total_setup_costs = @portfolio.setup_cost + @portfolio.properties.pluck(:setup_costs).inject(:+)

在创建列“设置成本”时,将列“设置成本”的默认值设置为0

如果我理解正确,每个投资组合都会有一个设置成本,您需要在投资组合的每个属性上添加该投资组合设置成本。每个房产的设置成本是单独的还是相同的?@DeepeshKakani每个投资组合都有单独的设置成本,每个房产都有单独的设置成本。但是假设投资组合A有房产X和房产Y,那么X和Y的投资组合设置成本是相同的,对吗?就像在这种情况下,你可以将其保留在投资组合本身上?@DeepeshKakani-nope,它可能是其他的EntrelyOkay,因此在这种情况下,你可以在联接表上添加一些列,类似于Danish给出的答案,你可以在PropertyPortfolioLink上添加相关列,这对你有用吗?