Rails 3 and fields_for with activemodel (tableless) object - ruby-on-rails

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?

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.

Welldan97 brings up a very important point. You need the persisted? method. I was getting an undefined method for the model name earlier. Check my gist out. It works, but not perfect by any means. https://gist.github.com/2638002

Right now this is pretty hard to do with Rails 3.x. That will change with Rails 4 with the advent of ActiveModel::Model which will give all the base methods for your model to be ActionPack compatable.
However until Rails 4 is released a good standard to make your model ActionPack compatible is the ActionModel::Model module itself. It "should" work with the current stable Rails. Check it out
How you choose to implement this is your decision, but I would probably just download the file and throw it in my application's lib directory. That way I could just include it using
class Book
include ActiveModel::Model
end
Easy Rails Form compatibility for custom models.

Try this:
f.fields_for 'books[]', book do |bf|

Related

undefined method `map' for "1,2":String

I need to pass an array in a params, possible? Values can be, for example, ["1","2","3","4","5"] and these are strings but needs to eb converted to integers later.
I use a react_component in between a rails form_for. The html is like this:
<input type="hidden" name="people_id" id="people_id" value={this.state.people} />
The people array looks like this:
How can I pass the array in the value of the hidden field? The server error I got was
Im trying to do something like this in a model:
ids = params[:people_id]
ids.map do |b|
Foo.create!(people_id: b.to_i)
end
If I ids.split(",").map I get symbol to int error.
Edit:
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Still not sure what the issue is as nothing works. Here is a minimal reproduction of my code:
This answer is my react component and that's how I add to the array. Still in the component, I have the hidden field:
<input type="hidden" name="[people_id][]" id="people_id" value={this.state.people} />
_form.html.erb:
<%= form_for resource, as: resource_name, url: registration_path(resource_name), :html => { :data => {:abide => ''}, :multipart => true } do |f| %>
<!-- react component goes here -->
<%= f.submit "Go", class: "large button" %>
<% end %>
The story is, guest can select few people during registration in one go. Those people will be notified when registration is complete. Think of it as "I am inviting these people to bid on my tender". Those numbers, in the array, are user_ids.
users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
# POST /resource
def create
super do |resource|
ids = params[:people_id].pop # logs now as "people_id"=>["1,2"]
resource.save!(ids.split(",").map |b| Foo.create!(people_id: b.to_i) end)
end
end
end
New error on line resource.save:
no implicit conversion of Symbol into Integer
Edit #2
If I only have, in the create method:
ids.split(",").map do |b|
resource.save!(Foo.create!(people_id: b.to_i))
end
It works! Foo is created two times each with the correct people_id.
Because I am creating more objects: Bar, I do not know how to do that in:
resource.save!(<the loop for Foo> && Bar.create!())
The flow must be:
Device creates the User
Foo is created with the loop
Bar is created
etc
It has to be done that way as an User object is created on the fly.
In Rails you use parameter keys with brackets on the end to pass arrays.
However you should not concatenate the values as a comma seperated list but rather send each value as a seperate param:
GET /foo?people_ids[]=1&people_ids[]=2&people_ids[]=3
That way Rails will unpack the parameters into an array:
Parameters: {"people_ids"=>["1", "2", "3"]}
The same principle applies to POST except that the params are sent as formdata.
If you want a good example of how this works then look at the rails collection_check_boxes helper and the inputs it generates.
<input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
<label for="post_author_ids_1">D. Heinemeier Hansson</label>
<input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
<label for="post_author_ids_2">D. Thomas</label>
<input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
<label for="post_author_ids_3">M. Clark</label>
<input name="post[author_ids][]" type="hidden" value="" />
Updated:
If you intend to implement you own array parameters by splitting a string you should not end the input with brackets:
<input type="hidden" name="[people_id][]" value="1,2,3">
{"people_id"=>["1,2,3"]}
Notice how people_id is treated as an array and the input value is the first element.
While you could do params[:people_id].first.split(",") it makes more sense to use the correct key from the get go:
<input type="hidden" name="people_id" value="1,2,3">
Also you don't really want to wrap the "root" key in brackets. Thats used in rails to nest a param key in a hash eg. user[name].

Rails for nested array hidden input field in form (Haml)

What would be a better "Rails way" of doing it
- shops.map(&:id).each do |id|
<input id="p_shop_ids_#{id}" name="p[shop_ids][]" type="hidden" value="#{id}" />
I recently read that in Haml is in this sense downwards compatible. But it feels like it should be done with the rails checkbox helper instead
You can use the hidden field helper.
Based on #Sontya's comment (thanks!!)
- shops.map(&:id).each do |id|
= hidden_field_tag "p[shop_ids][]", id, id: "p_shop_ids_#{id}"
produces the correct output (I had to add the id-option)

mass updating attributes

I am using Sinatra but I am guessing this also applies to Rails (if not, please remove the tag or let me know and I will remove it).
I have a ActiveRecord::Base class User. It has tons of attributes and I am displaying a page that will allow someone to update the a particular user. Problem is, I have a hard time implementing the update functionality in a DRY manner. What I mean is, when I get the params with a POST request, I can do:
a_user.update_attributes params
because params contains bnch of other crap too (like :splat - what's that?) and it will throw an unknown attribute error. What I instead have to do is this:
a_user.update_attributes {:attrA => params[:attrA],
:attrB => params[:attrB], ...etc }
(keep in mind there are A LOT of attributes)
Is this how I should do this? To me, for some reason...it doesn't feel right. If for example, I have another Model that needs to be updated in a similar manner, I have to rewrite manually all attributes again.
What I am looking for is somethign like:
a_user.filter_and_update_attributes params
where filter_and_update_attributes automatically filters params of any bad/unknown attributes and I can use this anywhere with any models with have to rewrite so much useless code.
Thanks
If you structure your form like this:
<form action="/users" method="post">
<input id="user_email" name="user[email]" type="text">
<input id="user_name" name="user[name]" type="text">
<input id="user_phone_number" name="user[phone_number]" type="text">
...
<input id="user_email" name="user[email]" type="text">
<input name="commit" type="submit" value="Submit">
</form>
you should be able to use the params like this:
#user.update_attributes params[:user]
When you name your html fields like user[email], the params hash looks like:
{ user: { email: "example#example.com", name: "Example" } }
So using params[:user] gets you that nested hash of parameters that belong to the user.
You can filter a hash using select. Find a list of all attributes of your model and test if the keys are in that list:
attrs = a_user.attributes.keys - User.protected_attributes.to_a
a_user.update_attributes params.select {|k,v| attrs.include?(k)}

Creating a form with unknown fields and storing those fields into a serialized filed in my model

I have a form that will have both a dynamic set and a known set of fields. I need a way of storing the dynamic fields in the database and I have decided on storing them in a serialized field, as I will not need to search on the data, and I just need it stored and recalled when needed.
class MyApplication < ActiveRecord::Base
has_one :applicant
belongs_to :member
serialize :additional_fields, Hash
accepts_nested_attributes_for :applicant, :additional_fields
I was thinking of having the form return the fields as an additional_fields_attributes and somehow have the model look after storying the hash into the additional_fields section. Im not sure if I have to go as far as using something like method missing to look after this, or if I should scrap the accepts_nested_attributes_for and handle it on my own.
Does anyone have any thoughts?
Thanks! Ryan
I just tested what you suggest.
You don't need: accepts_nested_attributes_for :additional_fields
Just add in your form html like:
<input name="my_application[additional_fields][first]" type="text" />
<input name="my_application[additional_fields][second]" type="text" />
it will save a Hash with keys: first and second
You could put in your model an array of fields, say in your User model:
FIELDS= ["item1", "item2"]
In your view:
<% User::FIELDS.each do |field|%>
<input name="my_application[additional_fields][<%= field %>]" type="text" />
<% end %>
I ended up using this tutorial http://www.kalzumeus.com/2009/11/17/practical-metaprogramming-with-ruby-storing-preferences/ which worked really well.
Thanks for your help!

rails fields_for with ajax

I am building a dynamic form builder.. And i have a problem which i can't seem to fix.
So i have a db table called "forms"
forms can have "fields"..
The problem is that when a user creates a new 'field' (click add-field) then it should ajax the new field for .. that field.
The problem is that i can't just do something like this:
<%= Form.fields_for Field.new do |field| %>
<%= field.text_field :name%>
<% end %>
Does anybody have an idea? Yes i watch railscasts, yes i googled, yes i found the "complex-forms' repo on github.
But no luck (yet)
If you want an all javascript approach (instead of calling your server to produce the field names) then basically you just need to increment the field names for any new fields.
For example, if you have
class Form < ActiveRecord::Base
has_many :fields
accepts_nested_attributes_for :fields
and the HTML in the form has an input field that has something like
<label for="form_fields_attributes_0_name">
<input id="form_fields_attributes_0_name" name="form[fields_attributes][0][name]" type="text" />
then you need to write some javascript to make it look like
<label for="form_fields_attributes_1_name">
<input id="form_fields_attributes_1_name" name="form[fields_attributes][1][name" type="text" />
You can do something like
$('#form_fields_attributes_1_name').attr('id').split('_');
and
$('#form_fields_attributes_1_name').attr('name').split(/\]\[/);
to get at those numbers.
Here's an example which is refactored here.

Resources