I'm trying to create a model form that will allow me to add references by name via a <select> tag.
e.g.
In the database there are already RefModels with ref_name = "a", ref_name = "b", ref_name = "c".
Form:
<%= form_for #model %>
<%= f.label :ref_models, "Referenced Models:" %>
<%= f.select :ref_models, ["a","b","c"], {}, {:multiple => true} %>
Controller:
def create
#model = Model.new(model_params)
params[:model][:ref_models].each do |ref|
#ref = RefModel.where("ref_name = ?", ref)
#model.ref_models << #ref
end
respond_to do |format|
...
end
end
In my logs I'm getting this error:
Started POST "/models" for 127.0.0.1 at 2013-06-25 16:20:48 -0300
Processing by ModelssController#create as JS
Parameters: {"utf8"=>"✓", "models"=>{..., "ref_models"=>["a", "b", "c"], ...}, "commit"=>"Create"}
Completed 500 Internal Server Error in 2ms
ActiveRecord::AssociationTypeMismatch (RefModel(#70144007274440) expected, got String(#70144005442620)):
app/controllers/models_controller.rb:52:in `create'
What's the problem?
Note:
I changed the actual model names for "model" and "ref_model" to generalize.
EDIT:
The error occurs on this line:
#model = Model.new(model_params)
The error comes from this part:
#model = Model.new(model_params)
I'm pretty sure your model_params is actually params[:model]. If yes, it means it tries to create a record for Model with the attribute ref_models and the values contained in params[:model][:ref_models]
You should take off the params[:model][:ref_models] before passing it to the Model.new(params[:model]):
def create
ref_models = params[:model].delete(:ref_models)
#model = Model.new(params[:model])
ref_models.each do |ref|
#ref = RefModel.where("ref_name = ?", ref)
#model.ref_models << #ref
end
respond_to do |format|
...
end
end
Do these ref_models have IDs as well as names? If so, you can get Rails to do the heavy lifting for you.
In your view, do:
<%= f.select :ref_model_ids, RefModel.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>
Then, you can take out the custom code from your controller, Rails knows how to link those models up appropriately. That's assuming you have a table like model_ref_model with columns for model_id and ref_model_id.
Hope that helps...
Related
I'm stuck on this... Asked a few questions already, but can't get my head around this.
I have a form for adding bibliography (model Biblio) that has a simple validation field on title of the bibliography.
Validation always fails, even when valid data is added.
MODEL
class Biblio < ApplicationRecord
# validates_presence_of :auteurs => there's a nested form too but
# I commented it out in order to isolate the problem
accepts_nested_attributes_for :auteurs
validates :titre, presence: true
CONTROLLER
(full text and I didn't translate in order to avoid typos)
def new
#biblio = Biblio.new(params_biblio)
#biblio.auteurs.build
end
def nouveau
# this method renders 'nouveau.html.erb',
# that contains the form allowing the addition of bibliography
#biblio = Biblio.new
if params[:id] # id is an optional parameter
#auteur = Auteur.find(params[:id])
#idauteur = #auteur.id
end
end
def ajouter
# is the method that treats the post form that was sent
#biblio = Biblio.new
if #biblio.save
# the 4 following lines are irrelevant here as they only add the
# second and subsequent authors to the join table.
# No validation and works fine.
b = auteurs_devises(params[:biblio][:auteurs])
aut = b.map do |var|
lett = Auteur.find(var)
lett.biblios << #biblio
end
redirect_to voir_biblio_url(Biblio.last)
else
if params[:id]
#auteur = Auteur.find(params[:id])
#idauteur = #auteur.id
end
render 'nouveau'
end
end
THE VIEW:
<%= form_for :biblio, url: administration_ajoute_biblio_url do |f| %>
<%= f.fields_for :auteurs do |aut| %>
<%= aut.label t('auteur') %>
<%= aut.text_field :nom , :name =>"biblio[auteurs][nom]", data: {autocomplete_source: auteurs_enum_path} %>
<% end %>
<%= f.label t('titre').capitalize %>
<%= f.text_field :titre %>
These are the params that are sent to the method nouveau:
Started POST "/administration/biblios/nouveau" for ::1 at 2017-02-07 21:28:28 +0100
Processing by Administration::BibliosController#ajouter as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+354h4M0Tg+BX21XAuQ6YMKS0BGQ8UjET8paKjkGCBsS1up1lB131KsoaCy563X4juDz0EJy46WgXbHcu51Kgw==", "biblio"=>{"auteurs"=>{"nom"=>"Godding"}, "titre"=>"Test Tuesday Evening", "soustitre"=>"", "recueil"=>"", "editeur"=>"", "annee"=>"", "isbn"=>"", "genre"=>"source", "revue_id"=>"", "revue_no"=>"", "revue_page"=>"", "lieu"=>"", "commentaire"=>""}, "commit"=>"Enregistrer"}
(0.2ms) BEGIN
(0.1ms) ROLLBACK
Rendering administration/biblios/nouveau.html.erb within layouts/messources
CONTROLLER AGAIN
def params_biblio
params.require(:biblio).permit(
:titre,
:soustitre,
:editeur,
:isbn,
:recueil,
:genre,
:revue_id,
:revue_no,
:revue_page,
:annee,
:lieu,
:commentaire,
auteurs: [:nom] )
end
For the sake of completeness, here's my routes.rb:
# ADMINISTRATION => BIBLIOGRAPHIE
get 'biblios/nouveau(/:id)' => 'biblios#nouveau', as: 'nouvelle_biblio'
post 'biblios/nouveau(/:id)' => 'biblios#ajouter', as: 'ajoute_biblio'
delete 'biblios/supprime/:id' => 'biblios#supprime', as: 'supprime_biblio'
get 'biblios/maj/:id' => 'biblios#cherche_maj', as: 'maj_biblio'
patch 'biblios/maj/:id' => 'biblios#maj', as: 'patch_maj_biblio'
I must be blind. I'm doing something wrong... I put a title to this bibliography ('Test Tuesday Evening'), this is the only field on which I left a validation, and despite this, validation always fails.
I am having some trouble saving arrays in Rails.
Rails version: 4.2.3 | Ruby version: 2.2.1 | DB: PostgreSQL
In my view, I have a collection of check boxes that shows the conferences that my member attended.
<%= f.fields_for :conferences_member do |conference| %>
<%= collection_check_boxes(:conferences_member, :conference_id, #all_conferences, :id, :name)%>
<% end %>
I put a break point (binding.pry) after the create action in my MembersController, and surprisingly, it shows the selected check boxes:
Processing by Database::MembersController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"XYZ==",
[...] "conferences_member"=> {"conference_id"=>["3", "5", ""]}, [...]
Now, if I go to rails c, and type ConferencesMember.last to check what was saved, I get:
pry(main)> ConferencesMember.last
ConferencesMember Load (0.5ms) SELECT "conferences_members".* FROM
"conferences_members" ORDER BY "conferences_members"."id" DESC LIMIT 1
=> nil
These are my associations:
#=> member.rb
has_one :conferences_member
accepts_nested_attributes_for :conferences_member, allow_destroy: true, reject_if: :all_blank
#=> conferences_member.rb
serialize :conference_id, Array
belongs_to :member
#=> members_controller.rb
params.require(:member).permit( [...]
:conference_member_attributes => [:id, :member_id, :conference_id => []],
[...])
I want to thank you in advance. I've tried almost everything here on StackOverflow, but I don't see my error.
Thank you again.
EDIT:
More of my MembersController:
def new
#member = Member.new
#member.build_conferences_member
end
def create
#member = Member.new(member_params)
binding.pry
end
The log doesn't show any error, it just shows that conferences were not saved at all.
First, your field needs to be renamed to nest the :conference_id in :conferences_member_attributes (not in :conferences_member as you do now). Take advantage of the form object yielded by fields_for:
<%= f.fields_for :conferences_member do |conference| %>
<%= conference.collection_check_boxes :conference_id, #all_conferences, :id, :name %>
<% end %>
You also need to actually save the record in the create action: Member.new builds the record but does not save it. Typically, the create action branches based on whether the record saved or did not (due to validations). So you might rewrite this method like so:
def create
#member = Member.new(member_params)
# when #member.save returns true, it saved to the db successfully
if #member.save
redirect_to members_path, notice: "Member #{#member.id} saved!"
# otherwise, it didn't save because of a validation error, so we render the error
# to the user and give them a chance to fix it
else
flash[:error] = "Member didn't save: #{#member.errors.full_messages.to_sentence}"
render :new
end
end
Lastly, to make sure your data gets through your strong parameters, check your logs for any messages that parameters were filtered out. The messages look like:
Unpermitted parameters: your_favorite_attribute
I'm submitting a form with 2-4 objects at once, depending on how many the parent has. I realize that this is probably unconventional, but I really wanted the user to be able to edit all of the objects at once on one form. On my form, I'm doing:
<%= simple_fields_for "derps[]", derp do |f| %>
<% end %>
Then I'm doing this in the controller:
def update
#derps = []
#rejects = []
derps_params.each do |key, hash|
derp = Derp.find(key)
derp.assign_attributes(hash)
#rejects << derp unless derp.save
end
if #rejects.empty?
redirect_to #parent, flash: {success: 'Derps were successfully updated.'}
else
#derps = #rejects
render :edit
end
end
Lets say there are two objects - the params are coming through as:
"derps"=>{"1"=>{"attribute"=>"39", "another_attribute"=>"serp", "a_third_attribute"=>"yerp"}, "2"=>{"attribute"=>"30", "another_attribute"=>"49", }}
I had this working in Rails 3 without strong params. I'm upgrading to rails 4 and I'm struggling with how to get this working - I keep getting "Unpermitted parameters: 1, 2"
I'm assuming I need to do something like:
def mashes_params
params.require(:derps).permit(
id: []
or
def mashes_params
params.require(:derps).permit(
:id,
Something along those lines, but I've tried it every way I can think of without luck.
Any ideas here?
I've found that the command line is immensely helpful for debugging Strong Parameters in Rails 4. Here's how I tested your problem in the console:
rails c # From within your project directory, short for 'rails console'
params = ActionController::Parameters.new( { derps: { 1 => { attribute: 39, another_attribute: "serp" }, 2 => { attribute: 30, another_attribute: 49 } } } )
params # To make sure that the object looks the same
permitted = params.require( :derps ).permit( 1 => [ :attribute, :another_attribute ], 2 => [ :attribute, :another_attribute ] )
permitted # To see what you'd get back in your controller
Hopefully with this tool, you'll be able to debug anything that my answer didn't provide more easily than trial and error.
Final Edit (hopefully):
Had to rethink this from the ground up. I came to the conclusion: Since :id works as a wildcard, but is not allowed as the key of the hash, why not always make the keys 1-4, so I can whitelist them explicitly, then get the ID from a key-value in the hash, much like is done in traditional form nesting? Thats how I ended up solving it. Here's the final implementation that I have working:
<% i = #parent.derps.index(derp) + 1 %>
<%= simple_fields_for "derps[#{i}]", derp do |f| %>
<%= f.hidden_field :id, value: derp.id %>
<%= render "rest_of_the_fields" %>
<% end %>
Then in the controller:
def update
#derps = []
#rejects = []
derp_params.each do |key, hash|
derp = Derp.find(hash.delete("id"))
derp.assign_attributes(hash)
#rejects << derp unless derp.save
end
if #rejects.empty?
redirect_to #parent, flash: {success: "Derps updated successfully."}
else
#derps = #rejects
render :edit
end
end
Then here are the strong params:
def derp_params
p = [:id, :attribute_1, :another_attribute, ...]
params.require(:derps).permit(
"1" => p, "2" => p, "3" => p, "4" => p
)
end
Phew. Hope this helps someone.
The absolute best solution I've seen is here:
def product_params
properties_keys = params[:product].try(:fetch, :properties, {}).keys
params.require(:product).permit(:title, :description, properties: properties_keys)
end
I made one more change to iterate through the unnamed keys since my property_keys have more nested keys and values:
response_keys = params[:survey][:responses].try(:fetch, :properties, {}).keys
params.require(:survey).permit(responses: response_keys.map {|rk| [rk => [:question_id, :answer_id, :value]]})
Here is the approach I am currently using. You can permit each nested params one by one like this:
params = ActionController::Parameters.new(
"derps" => {
"1" => {
"attribute" => "39",
"another_attribute" => "serp",
"a_third_attribute" => "yerp"
},
"2" => {
"attribute" => "30",
"another_attribute" => "49"
}
}
)
# => <ActionController::Parameters {"derps"=>{"1"=>{"attribute"=>"39", "another_attribute"=>"serp", "a_third_attribute"=>"yerp"}, "2"=>{"attribute"=>"30", "another_attribute"=>"49"}}} permitted: false>
params.fetch(:derps).map do |i, attrs|
[
i,
ActionController::Parameters.new(attrs).permit(
:attribute,
:another_attribute,
:a_third_attribute,
)
]
end.to_h.with_indifferent_access
#=> {"1"=><ActionController::Parameters {"attribute"=>"39", "another_attribute"=>"serp", "a_third_attribute"=>"yerp"} permitted: true>, "2"=><ActionController::Parameters {"attribute"=>"30", "another_attribute"=>"49"} permitted: true>}
Here is a sort of dirty way of accomplishing this which builds on the answer above by Greg Blass
This can handle an infinite number of indexes with nested params
def foo_bar_params
num_keys = params[:foo_bars].keys.size
the_params = [:id, :attr1, :attr2, :another]
permit_hash = {}
i = 0
while i < num_entries
permit_hash[i.to_s] = the_params
i += 1
end
params.require(:foo_bars).permit(permit_hash)
end
Im sure there is a fancier way to do this, but this way is readable and I can easily tell what is going on...and most importantly it works
This creates and saves a new row to my database. The problem is that I have a checkbox in my view file for a boolean value, but no matter whether the box is checked or not, the new row is always false. I also can't get any of the other attributes to show up as anything other than nil. Any ideas?
This is my view is:
<%= form_for(#setting) do |s| %>
<div class="field" >
<%= s.label :my_setting_attribute %>
<%= s.check_box(:my_setting_attribute) %>
</div>
<div class="actions">
<%= s.submit "Submit" %>
</div>
<% end %>
And my controller:
def new
#setting = Setting.new
end
def create
#setting = Setting.new(params[:setting])
if #setting.save
redirect_to :action => 'index', :id => #setting.id
else
redirect_to :action => 'error'
end
end
I think I have my route file set correctly:
resources :settings do
collection do
get :index
post 'settings/new'
get 'settings/show'
end
end
Here's the development log excerpt:
Started POST "/settings" for 10.7.94.191 at 2011-07-25 20:30:11 -0400
Processing by SettingsController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"xxxxxxxxxxx=", "setting"=>{"my_setting_attribute"=>"1", "other_setting_attribute"=>"hello"}, "commit"=>"Submit"}
ESC[1mESC[36mUser Load (0.1ms)ESC[0m ESC[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1ESC[0m
ESC[1mESC[35mSQL (0.1ms)ESC[0m BEGIN
ESC[1mESC[36mSQL (1.0ms)ESC[0m ESC[1mdescribe `settings`ESC[0m
ESC[1mESC[35mAREL (0.3ms)ESC[0m INSERT INTO `settings` (`facebook_token`, `twitter`, `user_id`, `created_at`, `updated_at`, `image_id`) VALUES (NULL, NULL, NULL, '2011-07-26 00:30:12', '2011-07-26 00:30:12', NULL)
ESC[1mESC[36mSQL (57.1ms)ESC[0m ESC[1mCOMMITESC[0m
Redirected to http://3000/settings?id=12
May not be the "correct" way of doing it but you could probably do this:
In your controller for the update and create method, check what the value of params[:my_setting_attribute] is. You may need to conditionally set the attribute to either "true" or "false".
e.g. perhaps it is returning "1" instead of true (which your log seems to indicuate), then you can set it yourself with something like #my_object.my_setting_attribute = true if params[:my_setting_attribute] == "1". Then probably add an else clause to set everything else to false, just to be safe.
I'm working on a moderating feature for my application, which is based on a basic scaffold structure. What I need, is to edit several records with the boolean parameter publised on false. In moderate.html I'm getting the list of all unpublished entries with the ability to change their parameters which, what and published. The error appears, when I'm trying to save the changes through the complete action.
ArgumentError in NamesController#complete
Unknown key(s): 7, 1, 4
The "7, 1, 4" are id of my unpublished records.
Here are the parts of my code:
#names_controller.rb
def moderate
#names = Name.find(:all, params[:name_ids], :conditions => {:published => false})
respond_to do |format|
format.html { render :action => "moderate" }
format.xml
end
end
def complete
#names = Name.find(params[:name_ids])
#names.each do |name|
name.update_attributes!(params[:name].reject { |k,v| v.blank? })
end
flash[:notice] = "Updated records!"
redirect_to names_path
end
#moderate.html.erb
<% form_tag complete_names_path do %>
<% #names.each do |name| %>
<fieldset>
<% fields_for "name_ids[#{name.id}]", name do |name_fields| %>
<%= name_fields.text_field :which %>
<%= name_fields.text_field :what %>
<%= name_fields.check_box :published %>
<% end %>
</fieldset>
<% end %>
<%= submit_tag "Ok" %>
<% end %>/
#routes.rb
ActionController::Routing::Routes.draw do |map|
map.connect 'moderate', :controller => 'names', :action => 'moderate'
map.resources :names, :collection => { :complete => :put}
map.root :names
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
I understand, that there's something wrong with the name_ids, but don'nt understand, what should I do.
Thank you in advance.
ruby 1.8.7 (2009-06-12 patchlevel 174)
[universal-darwin10.0] Rails 2.3.5
Rails log for moderate and complete actions:
Processing NamesController#moderate (for 127.0.0.1 at 2010-10-16 21:36:42)
[GET] [4;35;1mName Load (0.6ms)[0m
[0mSELECT * FROM "names" WHERE
("names"."published" = 'f') [0m
Rendering template within
layouts/names Rendering names/moderate
Completed in 12ms (View: 7, DB: 1) |
200 OK [http://localhost/moderate]
Processing NamesController#complete
(for 127.0.0.1 at 2010-10-16 21:36:49)
[POST] Parameters: {"commit"=>"Ok",
"authenticity_token"=>"CtmsjIavksOMSIArrdovkkzuZzHVjkenFFMO5bHIvgg=",
"name_ids"=>{"7"=>{"published"=>"0",
"what"=>"Партия", "which"=>"Крутая"},
"1"=>{"published"=>"1",
"what"=>"Россия", "which"=>"Единая"},
"4"=>{"published"=>"0",
"what"=>"Организация",
"which"=>"Молдавская"}}}
[4;36;1mName Load (0.4ms)[0m
[0;1mSELECT * FROM "names" WHERE
("names"."id" IN (7,1,4)) [0m
NoMethodError (You have a nil object
when you didn't expect it! You might
have expected an instance of Array.
The error occurred while evaluating
nil.reject):
app/controllers/names_controller.rb:47:in
complete'
app/controllers/names_controller.rb:46:in
each'
app/controllers/names_controller.rb:46:in
`complete'
Rendered rescues/_trace (110.3ms)
Rendered rescues/_request_and_response
(0.5ms) Rendering rescues/layout
(internal_server_error)
Likely you need to get just the keys from the name_ids hash. Try:
#names = Name.find(params[:name_ids].keys)
A separate problem is your reference to params[:name], which is nil. Did you mean (EDIT: use to_s to match the params key, lol):
#names.each do |name|
name.update_attributes!(params[:name_ids][name.id.to_s].reject { |k,v| v.blank? })
end
EDIT (brief-ish explanation):
What was happening was that you had a nested hash in the params, params[:name_ids]. It looked like:
"name_ids"=>{"7"=>{"published"=>"0", "what"=>"Партия", "which"=>"Крутая"}, "1"=>{"published"=>"1", "what"=>"Россия", "which"=>"Единая"}, "4"=>{"published"=>"0", "what"=>"Организация", "which"=>"Молдавская"}}
An ActiveRecord 'find' method can take an array of ids, but not a hash of values. What you were originally submitting to 'find' in this line:
#names = Name.find(params[:name_ids])
...was the value for params[:name_ids]:
{"7"=>{"published"=>"0", "what"=>"Партия", "which"=>"Крутая"}, "1"=>{"published"=>"1",
"what"=>"Россия", "which"=>"Единая"}, "4"=>{"published"=>"0", "what"=>"Организация",
"which"=>"Молдавская"}
When what you wanted was:
#names = Name.find(['7','1','4'])
which is what calling params[:name_ids].keys gives you.
The second problem was this line:
name.update_attributes!(params[:name].reject { |k,v| v.blank? })
There was no value ':name' in params, so calling 'reject' on it cause the 'no method' error -- there is no 'reject' method on the nil object. What you wanted was to update the attributes for the 'name' that corresponded to the particular name in the loop. This meant you wanted to get the values out of params[:name_ids][:id] where :id was the id of 'name'.
It all goes back to the way fields_for created the params to begin with. This line:
<% fields_for "name_ids[#{name.id}]", name do |name_fields| %>
meant that params would contain a hash called 'name_ids', with keys corresponding to name.id, that themselves would contain hashes of attributes that ActiveRecord could use in the update_attributes method.
There's a good bit of the famous Rails magic to keep track of in there -- does that help?