koosa
koosa

Reputation: 3040

Why is assign_attributes with array of ids for has_many association only associating one object?

I have a form where users can upload assets using ajax. This creates many Asset objects that I then want to associate with a Post object when it is created. I have a form_field named asset_ids that I update with the created Asset ids as they are created. When I create the Post object and populate its data with assign_attributes, only ONE association is created, no matter how many ids are there.

Asset model:

class Asset < ActiveRecord::Base

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

end

Post model:

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

An example of the posted data hash:

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

The example above assigns only one Asset (id 97) to the new Post, when I assign_attributes like so:

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

Upvotes: 1

Views: 1687

Answers (1)

koosa
koosa

Reputation: 3040

I had to make sure I was assigning the ids as an array:

@post.asset_ids = params[:post][:asset_ids].split(",")

Upvotes: 1

Related Questions