【问题标题】:How to set a value to the additional column of the join table in the Rails 4?如何为 Rails 4 中连接表的附加列设置值?
【发布时间】:2014-01-30 07:46:35
【问题描述】:


我有三个表:
product (id, name)
image (id, src)
product_images (product_id, image_id, position)
位置字段是产品图像的序号。
Product_images 是连接表。
Rails 4 中也有三种模型:

class Product < ActiveRecord::Base
  has_many :product_images, class_name: "ProductImage"
  has_many :images, through: :product_images
end

class Image < ActiveRecord::Base   
  has_many :product_images
  has_many :products, through: :product_images, foreign_key: :product_id

  accepts_nested_attributes_for :product_images, allow_destroy: true

end

class ProductImage < ActiveRecord::Base
  self.table_name = "product_images"

  belongs_to :product
  belongs_to :image

  #has_many   :images
  #accepts_nested_attributes_for :image, :allow_destroy => true
  #attr_accessible :position

end

在控制器中:

def test
  @pr  = Product.new name: "Super Sofa"
  @imgs = Image.find(19, 20)
  @imgs[0].position = 1
  @imgs[1].position = 2
  @pr.images = @imgs
  @pr.save
end

Rails 返回此错误: #Image:0x68696e8 的未定义方法 `position='

如何通过Image 模型将位置字段设置为product_images 表?是否可以?也许我对accepts_nested_attributes_of的理解有误。
在这种情况下,纯SQL可能是更好的方法吗?
谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-4


    【解决方案1】:
    product_images (product_id, image_id, position)
    

    你在产品图片下有位置属性,属于图片。

    def test
      @pr  = Product.new name: "Super Sofa"
      @imgs = Image.find(19, 20)
      @imgs[0].product_image.first.position = 1
      @imgs[1].product_image.first.position = 2
      @pr.images = @imgs
      @pr.save
    end
    

    您需要指定要更改的产品图片,因为您的图片可能有产品图片。如果你调用 position ,它必须在产品图片上,除非你这样做。

    class Image < ActiveRecord::Base
    def position
      self.product_images.first.position
    end
    end
    

    但这没有任何意义,因为 position 属性应该在 image 表而不是 product-images 表下。想一想。

    【讨论】:

    • 感谢您的回复。但是这两种变体都会产生错误:
      undefined method position=' for nil:NilClass&lt;br&gt; I have tried such code:&lt;br&gt; @imgs[0].product_images[0] = ProductImage.new position: 1 This code doesnt 会产生错误,但 position 字段为空。由于某种原因,@imgs[0].product_images[0] 在分配后是Nil
      >>位置属性应该在图像表而不是产品图像表下
      图像可能包含在多个产品中,因此每个product 的图像可能有不同的position
    猜你喜欢
    • 1970-01-01
    • 2017-08-07
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2018-08-04
    相关资源
    最近更新 更多