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].
Related
Part of the app i'm developing involves a form which has to create a product on the users shopify store and also create a row in my own database for an identical product (with a few extra bits of information).
Where i'm struggling is with the form itself, i can do this with a html based form, but i can't get a single ruby form to do both jobs. A shortened version of my controller create code is as follows;
def create
#item = Item.new
#item.item_title = params[:item_title]
#item.item_profit = params[:item_profit]
#new_product = ShopifyAPI::Product.new
#new_product.title = params[:item_title]
#new_product.save
#item.save
end
So as you can see i'm using the same params to set values for both the shopify product and the product in my own db. The HTML form looks like this:
<form action="/items/submit" >
<input type="text" name="item_title">
<br>
<input type="text" name="item_profit">
<br>
<br>
<input type="submit"/>
</form>
And it works fine, but how do i convert this into a ruby form that does the same job?
You can do like this:
form_tag('/items/submit')
text_field_tag 'item_title'
tag("br")
text_field_tag 'item_profit'
tag("br")
tag("br")
<%= submit_tag 'Save' %>
Instead of tag("br"), you can directly use < br />.
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)}
This is a follow-up to this question where's the appropriate place to handle writing the current_user.id to an object I have the following model. An item which has_many assets. I'm am using accepts_nested_attributes_for :assets in the item.
I'd like to assign the current_user.id value to each asset. Normally I just do #item.update_attributes(params[:item]) to save it. Is there a simple one line way of setting the user_id for each asset in this scenario?
Looking in dev log, I see the value here:
item[assets_attributes][10][asset]
Should I just iterate through all of these and set a user_id value?
thx
here's some more of the html (items -> menu_item; had left out above to simplify). The proposed controller sol'n below does not seem to work. I'm fine with doing at the level of controller. Any help appreciated.
<div class='image-row'>
<input id="menu_item_assets_attributes_18_asset" name="menu_item[assets_attributes][18][asset]" type="file" />
<input id="menu_item_assets_attributes_18_description" name="menu_item[assets_attributes][18][description]" size="30" type="text" />
</div>
<div class='image-row'>
<input id="menu_item_assets_attributes_19_asset" name="menu_item[assets_attributes][19][asset]" type="file" />
<input id="menu_item_assets_attributes_19_description" name="menu_item[assets_attributes][19][description]" size="30" type="text" />
</div>
<div class='image-row'>
<img alt="D5cc413a1748fb43b0baa2e32e29b10ac2efda10_huntbch_thumb" src="/images/371/d5cc413a1748fb43b0baa2e32e29b10ac2efda10_huntbch_thumb.jpg?1329917713" />
<div class='img-row-description'>
<label for="menu_item_assets_attributes_20_description">Description</label>
<input id="menu_item_assets_attributes_20_description" name="menu_item[assets_attributes][20][description]" size="60" type="text" value="here is my comment" />
<label for="menu_item_assets_attributes_20_destroy">Destroy</label>
<input name="menu_item[assets_attributes][20][_destroy]" type="hidden" value="0" /><input id="menu_item_assets_attributes_20__destroy" name="menu_item[assets_attributes][20][_destroy]" type="checkbox" value="1" />
</div>
This answer is probably a little bit muddier than your previous one.
If each asset must have an item, then it might be more sensible to remove the idea of an owning user from an asset entirely: you can always find the owning user by querying the attached item, something like #asset.item.user. However, if users can own assets independently of items, I don't think this will work for you.
If assets are always created in a nested manner for items, a before_create for the asset could assign the value you want. Something like this in asset.rb:
before_create :assign_user
def assign_user
self.user = self.item.user if self.item && self.item.user
end
Finally, if you just want to do it in the controller, Wolfgang's answer is really good and will add the user_id to each asset_attributes.
How about iterating over the params array and setting the value like so:
params[:item][:assets_attributes].map! do |asset_params|
asset_params[:user_id] = current_user.id
end
Now you can use update_attributes( params[:item] ) as before.
i have a hidden_tag like this in my form
<%= f.hidden_field :loc , {:multiple => true} %>
which renders to
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="">
currently am setting the business_loc value as a comma seperated string hoping rails would recognize when submit the form. But this is the value i got on the server side
"loc"=>["80.22167450000006,13.0454044"]
instead
"loc"=>[80.22167450000006,13.0454044]
how do i set the correct value in hidden field, so rails can understand it correctly.
You need to use multiple hidden fields, one for each element of the array of values.
For example:
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="80.22167450000006">
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="13.0454044">
...if you need code to dynamically add these with JS, here's a jQuery example:
var field = $('<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="13.0454044">');
var form = $('#your-form-id');
form.append(field);
I've found text_area's to make things work without having to add a bunch of hidden forms. Just set the value of the text area to something that looks like [1,31,51,61] and it should work, assuming in your model you have serialize :var
I had this same problem recently. My solution was to handle it on the server side by simply splitting the array at the comma. In my case it looks like this:
# thing_that_has_many_objects.rb <-- showing custom setter method from the model because my example involves using a virtual attribute
# params[object_ids] = ["1,2,3,4,5"] <-- from the form - note the format of array with only one element
def objects=(object_ids)
split_array = object_ids[0].split(',')
split_array.each do |id|
self.objects.build(object_id: id)
end
end
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.