在 rails 中管理关系
Maniging relations in rails
我正在开发一个应用程序,我必须创建一个模型 product
,其中有很多 pictures
和一个主要的 picture
。我想通过关系来模拟这种情况,而不是使用一个额外的布尔字段来判断一张图片是否是主图片。我认为解决方案是在 product
中使用 has_one
和 has_many
关系,从 link 到 picture
但我不知道该怎么做。
您将需要一些方法来将您的 "main" 图片与其他图片区分开来。这可以通过多种方式完成:
一个单独的数据库table,比方说,main_pictures
class Product
has_many :pictures
has_one :main_picture
end
或 Picture
上的一些其他属性。这可以是布尔值或其他字段。在下面的示例中,我们将在 pictures
table.
上使用名为 primary
的布尔属性
class Product
has_many :pictures
has_one :main_picture, -> { where(primary: true) }
end
我正在开发一个应用程序,我必须创建一个模型 product
,其中有很多 pictures
和一个主要的 picture
。我想通过关系来模拟这种情况,而不是使用一个额外的布尔字段来判断一张图片是否是主图片。我认为解决方案是在 product
中使用 has_one
和 has_many
关系,从 link 到 picture
但我不知道该怎么做。
您将需要一些方法来将您的 "main" 图片与其他图片区分开来。这可以通过多种方式完成:
一个单独的数据库table,比方说,main_pictures
class Product
has_many :pictures
has_one :main_picture
end
或 Picture
上的一些其他属性。这可以是布尔值或其他字段。在下面的示例中,我们将在 pictures
table.
primary
的布尔属性
class Product
has_many :pictures
has_one :main_picture, -> { where(primary: true) }
end