【问题标题】:Associate Model and Update Attribute关联模型和更新属性
【发布时间】:2012-11-15 11:35:05
【问题描述】:

我有 2 个具有直通关系的模型:

PortfolioItem
has_many :portfolio_item_images
has_many :images, :through => :portfolio_item_images

PortfolioItemImage
belongs_to :image
belongs_to :portfolio_item

我想将投资组合项目图像与投资组合项目相关联,并设置投资组合项目图像的位置。

现在我正在这样做:

i13 = PortfolioItem.create({:name => 'Portfolio Item 1'})
i13_img01 = Image.find_by_image_name('Portfolio_Item_Image.jpg')
i13.images << i13_img01
i13_portimg01 = i13.portfolio_item_images.find_by_image_id(i13_img01.id)
i13_portimg01.update_attributes(:position => 1)

这是相当复杂的,因为我正在设置关系,然后从我的图像 id 中找到直通记录,然后在投资组合项目图像上设置位置。

我感觉有一种更简洁的 Ruby/Rails 方式可以使用 ActiveRecord 执行此操作。但我在谷歌上没有找到任何东西。每次我用 Google 关联时,通常都会弹出 Rails 指南,但我在其中找不到信息。

另外,我对 Image 模型没有太多控制权。

感谢您的宝贵时间!

更新: 该图像也是先前创建的。所以我不能通过 PortfolioItem 创建它然后添加属性。谢谢!

【问题讨论】:

    标签: ruby-on-rails associations has-many-through


    【解决方案1】:

    我认为这应该符合您的需要:

    i13 = PortfolioItem.create({:name => 'Portfolio Item 1'})
    i13.portfolie_item_images.create(image: Image.find_by_image_name('Portfolio_Item_Image.jpg'),
                                     position: 1)
    

    【讨论】:

    • 嗨,阿德里安,感谢您的意见。但是,图像对象是先前创建的。我将编辑我的问题以突出显示这一点。再次感谢!
    • 我没有尝试创建图像对象,我仍然像你一样使用Image.find_by_image_name
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多