为什么assign_attributes与has_many关联的id数组只关联一个对象?

时间:2013-01-03 03:40:03

标签: ruby ruby-on-rails-3 activerecord has-and-belongs-to-many

我有一个表单,用户可以使用ajax上传资产。这会创建许多Asset对象,然后我想在创建Post对象时将其与Post对象关联。我有一个名为asset_ids的form_field,我在创建时使用创建的资产ID进行更新。当我创建Post对象并使用assign_attributes填充其数据时,无论有多少ID,都只创建一个关联。

资产模型:

class Asset < ActiveRecord::Base

  attr_accessible :caption, :image
  belongs_to :post
  has_attached_file :image, :styles => { :large => "600x600>", :medium => "300x300>", :thumb => "100x100>" }

end

发布模型:

class Post < ActiveRecord::Base

    attr_accessible :content, :post_date, :status, :title, :tag_list, :asset_ids, :as => :admin
    has_many :assets, :dependent => :destroy
    has_and_belongs_to_many :tags

    validates :content, :post_date, :title, :presence => true

end

发布数据哈希的一个示例:

{"title"=>"Test post", "status"=>"true", "post_date"=>"01/02/2013", "content"=>"&nbsp;Some content", "tag_list"=>"", "asset_ids"=>"97,102"}

上面的示例只为新帖子分配了一个Asset(id 97),当我像这样assign_attributes时:

@post = Post.new
@post.assign_attributes params[:post], :as => :admin

1 个答案:

答案 0 :(得分:1)

我必须确保将id分配为数组:

@post.asset_ids = params[:post][:asset_ids].split(",")
相关问题