在Rails中两次引用相同的模型

问题描述 投票:1回答:1

我在rails API中有两个模型(页面和图像),它们之间存在多对多关系。我希望能够在我的Page模型中的两个(最终更多)位置引用Image模型(通过image_ids:[])。

我想要一个“图像库”数组和一个“特色图像”数组返回,我有什么画廊工作,因为它现在应该,但我正在努力理解从这里去哪里。这甚至可能吗?

我觉得这不应该像我一样复杂,所以我真的很感激任何帮助 - 我是一个新的开发人员和新的rails。这就是我要的 :

"id": 34,
    "title": "Test Page Gallery",
    "featured_image": [
                 "images": [
                     {
                       "id": 12,
                       "title": "test img 2",
                       "image": {
                       "url": "/uploads/medium/image/11/image2.jpeg"
                        }
                     ]
                 ],
    "images": [
        {
            "id": 11,
            "title": "test img 1",
            "image": {
                "url": "/uploads/image/image/11/image1.jpeg"
        }, ....
     ]

这就是我得到的:

"id": 34,
    "title": "Test Page Gallery",
    "featured_image": "[]",
    "images": [
        {
            "id": 11,
            "title": "test img 1",
            "image": {
                "url": "/uploads/image/image/11/image.jpeg"
        }, ....
     ]

强烈的参数:

def page_params
  params.permit(:title, image_ids:[], featured_image: [image_ids:[]])
end

页面型号:

class Page < ApplicationRecord
  belongs_to :user
  has_and_belongs_to_many :images, class_name: "Image", join_table: "images_pages"
end

我将featured_image列定义为字符串,但我知道这可能是错误的。提前致谢!

mysql ruby-on-rails ruby-on-rails-5
1个回答
0
投票

我会说你有两种方法之一:

1)有两个单独的关联,为Image指定featured_images类名:

page.rb

has_and_belongs_to_many :images, join_table: "images_pages"
has_and_belongs_to_many :featured_images, class_name: Image, join_table: "featured_images_pages"

2)使用has_many through关联并在连接表上有一个标志,无论图像是否有特色:

page.rb

has_many :images, through: :images_pages
has_many :images_pages

images_pages.rb

class ImagesPages
  belongs_to :image
  belongs_to :page

  scope :featured, -> { where(featured: true) }
end

快速阅读后一种方法here

我总是喜欢has_many through关系的灵活性。

玩这些,看看是否有帮助 - 任何问题,让我知道,我会看到我如何定制/扩展:)

© www.soinside.com 2019 - 2024. All rights reserved.