Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 and fields_for with activemodel (tableless) object

I have a tableless model that I'm trying to generate some form fields for.

The form looks like so:

= form_for :users, url: users_path do |f|
  - books.each do |book|
    = f.fields_for :books, book do |bf|
      = bf.hidden_field :title, value: book.title
  = f.submit "Send"

What I'm expecting to be generated for each field is something like this:

<input name="users[books][][title]" type="hidden" value="Some Book Title">
<input name="users[books][][title]" type="hidden" value="Some Book Title">
<input name="users[books][][title]" type="hidden" value="Some Book Title">

However, what I'm actually getting is

<input name="users[books][title]" type="hidden" value="Some Book Title">
<input name="users[books][title]" type="hidden" value="Some Book Title">
<input name="users[books][title]" type="hidden" value="Some Book Title">

Which means when the form is submitted only the last input field is available as the previous two have been overwritten due to them referencing the same thing.

This works ok when the model has an active record backend but not when it's tableless.

Any suggestions?

like image 892
KJF Avatar asked Feb 20 '12 13:02

KJF


1 Answers

I think you need to add this to your users model

def books_attributes= attributes
  # do something with attributes
  # probably:
  # self.books = attributes.map{|k,v|Book.new(v)}
end

And also define persisted? method for Book instance. Make it just to return false.

And add f for your fields_for in view:

= f.fields_for :books, book do |bf|

I hope this will work.

like image 124
welldan97 Avatar answered Nov 14 '22 21:11

welldan97