Rails rails 4 的表关联的问题

yeyong14 · 2013年07月04日 · 最后由 Victor 回复于 2013年10月30日 · 3555 次阅读

一个一对多的表

class Product < ActiveRecord::Base
  has_many :tags

数据表是这样的

class AddProductIdToTag < ActiveRecord::Migration
  def change                   
    add_column :tags, :product_id, :string
  end
end

视图里面是怎样的 <%= text_field :tags %> 在控制台就是这样的

=>ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Tag 

在 Rails3 还是好好的。怎么到了 Rails4 就这样了,是我那里配置的不对的吗?

We start by creating a migration: depot> rails generate migration combine_items_in_cart This time, Rails can’t infer what we are trying to do, so we can’t rely on the generated change() method. What we need to do instead is to replace this method with separate up() and down() methods.

class CombineItemsInCart < ActiveRecord::Migration
    def up
        Cart.all.each do |cart|
            sums=cart.line_items.group(:product_id).sum(:quantity)
            sums.each do |product_id,quantity|
                if quantity>1
                    cart.line_items.where(product_id:product_id).delete_all
                    item=cart.line_items.build(product_id:product_id)
                    item.quantity=quantity
                    item.save!
                end
            end
        end
    end
    def down
        LineItem.where("quantity>1").each do |line_item|
            line_item.quantity.times do
                LineItem.create cart_id: line_item.cart_id,product_id: line_item.product_id,quantity:1
            end
            line_item.destroy
        end
    end
end

新版的 agile web development with rails 4 beta 里面的。

今天遇到类似问题,原来 Associations in Rails 4 return a CollectionProxy instead of an Array 建议读一下 http://olivierlacan.com/posts/associations-in-rails-4/

需要 登录 后方可回复, 如果你还没有账号请 注册新账号