Cem Baykam
Cem Baykam

Reputation: 537

Rails inserting multiple records for single model

How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field. I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save 

And still nothing is saved.

Upvotes: 2

Views: 4971

Answers (2)

BitOfUniverse
BitOfUniverse

Reputation: 6021

posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)

Upvotes: 7

mportiz08
mportiz08

Reputation: 10308

is this what you're trying to do?

posts = []
posts << Post.new(:title => "title 1")
posts << Post.new(:title => "title 2")

posts.each do |post|
  post.save
end

Upvotes: 6

Related Questions