Rails5, nested form, undefined param - ruby-on-rails

Huston, we have a problem:
class FirstModel
has_many :merged_models
has_many :second_models, :through => :merged_models
end
class SecondModel
has_many :merged_models
has_many :first_models, :through => :merged_models
end
class MergedModel
belongs_to :first_model
belongs_to :second_model
end
Form:
<%= form_for(first_model) do |f| %>
<%= f.fields_for :merged_model do |ff| %>
<%= ff.label :date %>
<%= ff.date_select :start_date %>
Problem:
Processing by FirstModelsController#create as HTML Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"f+D8AaVzM6ahrUyo/nwxISFEleVrXGxo8m30sIiLIe7gvG8J9KfONjuT09j6z3M4Rvw+n3Hm6PMddOtfbgjt5g==",
"first_model"=>{"first_name"=>"yyyy", "last_name"=>"yyy",
"merged_model"=>{"start_date(1i)"=>"2017", "start_date(2i)"=>"2",
"start_date(3i)"=>"28", "second_model_id"=>"1"}}, "commit"=>"Create"}
Unpermitted parameter: merged_model Unpermitted parameter:
merged_model
First model's controller's strong params:
params.require(:first_model).permit(:first_name, :last_name, merged_models_attributes: [:id, :start_date])
First model acccepts nested attributes of merged model:
accepts_nested_attributes_for :merged_models
However, after creating a FirstModel, MergedModel does not get created. Tried to create it in form:
<%= f.fields_for :merged_model [first_model.merged_models.build] do |ff| %>
But got:
no implicit conversion of MergedModel into Integer
Not completely understand what that means..
Also tried creating a new MergedModel from a FirstModel's create action, with a bang:
#merge_model = MergedModel.create!
And got the same error - no implicit conversion...
Could anyone explain more about this? I feel its about passing an Array of my MergedModel's params into MergedModel's params...? I am totally lost here...

Your form should have fields_for :merged_models instead of just merged_model.

On fresh installs of Rails5 applications, belongs_to implies optional: false by default (previously called required: true).
You need to create a MergedModel both with FirstModel AND SecondModel associated...
It looks like you are trying create a MergedModel only with a FirstModel associated, if SecondModel is optional, you need to say that for belongs_to with...
belongs_to :second_model, optional: true

Related

How do I update Rails object when object to update is only determined in the form itself?

I'm looking to update a record but not in the standard Rails way in a form on the same controller. My form works fine there. I have a form in a different controller/view called Shoes.
The problem I'm having is the record a user is updating isn't a static record that can be pulled from the url (I think that's how Rails pulls generically - I'm learning so please don't decimate me for this if I'm not completely right here). When a user clicks an item to add/update to their client_sub_folder, the two collection_select options in the form allow the user to select which client_folder and client_sub_folder they are adding to and subsequently that will determine which client_folder and client_sub_folder the item they are adding will go to/update.
I'm using Devise for authentication on the Designer model.
How do I do this?
My error message:
No route matches {:action=>"show", :client_folder_id=>nil, :controller=>"client_sub_folders", :name_prefix=>"client_folder_"} missing required keys: [:client_folder_id, :id]
I assume some JQuery magic is going to be needed here.
Models:
class Designer < ApplicationRecord
has_many :client_folders, dependent: :destroy
has_many :client_sub_folders, through: :client_folders
accepts_nested_attributes_for :client_folders
accepts_nested_attributes_for :client_sub_folders
end
class ClientFolder < ApplicationRecord
belongs_to :designer
has_many :client_sub_folders, dependent: :destroy
accepts_nested_attributes_for :client_sub_folders
end
class ClientSubFolder < ApplicationRecord
belongs_to :client_folder
end
shoes/index.html.erb
<%= form_for([Designer.current_designer.client_folders,#sub_client_folder], url: client_folder_client_sub_folder_path(#client_sub_folder), method: :patch) do |f| %>
<%= f.collection_select :client_folders, :client_folder_ids, Designer.current_designer.client_folders, :id, :client_name, {include_blank: true}, {id: "get-folder"} %>
<%= f.grouped_collection_select :client_sub_folders, :client_sub_folder_ids, Designer.current_designer.client_folders.order(:client_name), :client_sub_folders, :client_name, :id, :room_name, {include_blank: true}, {id: "get-sub"} %>
<%= f.submit %>
<% end %>

Unpermitted parameter for join table via multiple select in Rails

I'm running into an error when nesting parameters in Rails 5: Unpermitted parameter: specialties
I have an Expertise model:
class Expertise < ApplicationRecord
has_many :buckets, through: :specialties
has_many :specialties
end
A Bucket model:
class Bucket < ApplicationRecord
has_many :expertises, through: :specialties
has_many :specialties
end
And a Specialty model:
class Specialty < ApplicationRecord
belongs_to :expertise
belongs_to :bucket
end
I'm trying to allow the User to edit his or her Expertises and adjust the Specialties associated with them. The #buckets are passed in from the controller, and the form currently looks like this:
<%= form_for(expertise) do |f| %>
<%= f.fields_for :specialties do |s| %>
<%= s.collection_select :bucket_ids, #buckets, :id, :name, {}, { multiple: true, class: "input" } %>
<% end %>
<% end %>
I based the form on this answer.
Here's the relevant snippet from the ExpertisesController:
def expertise_params
params.require(:expertise).permit(:user_id, :name, :rating, :description, specialties_attributes: [:id, :expertise_id, :bucket_id, :_destroy, bucket_ids: []])
end
And here are the parameters that are being passed in:
Parameters: {"expertise"=>{"specialties"=>{"bucket_ids"=>["", "1"]}, "description"=>""}, "id"=>"97"}
Specialties should be an array, right? I'm not sure how to do that.
The aim is to easily enable the User to select from the available Buckets (#buckets) to toggle his or her Expertise Specialties on or off. So let's say there are 5 Buckets available, the User would only be able to toggle on/off 5 possible Specialties for that Expertise.
Unpermitted parameter: specialties
You didn't set up accept_nested_attributes_for which spits out with that error
class Expertise < ApplicationRecord
has_many :specialties
has_many :buckets, through: :specialties
accepts_nested_attributes_for :specialties
end
When I try that, the nested fields_for form doesn't return any
specialties and so the HTML element is empty. Then, when I try to use
#expertise.specialties.build, I get undefined method bucket_ids for
Specialty because bucket_ids isn't actually an attribute, but
bucket_id is. Worth keeping in mind that the User needs to be able to
toggle multiple Specialties, each of which is tied to a Bucket (via a
bucket_id), and from what I've ready I'm supposed to use bucket_ids
(the plural) there
You don't need to have plural form(_ids) just because to accept multiple values. Just keep bucket_id to accept multiple values. And don't forget to build the associated model in the controller
def new
#expertise = Expertise.new
#expertise.specialties.build
end
Change bucket_ids to bucket_id in the form
<%= s.collection_select :bucket_id, #buckets, :id, :name, {}, { multiple: true, class: "input" } %>
And finally, expertise_params should be
def expertise_params
params.require(:expertise).permit(:user_id, :name, :rating, :description, specialties_attributes: [:id, :expertise_id, :_destroy, bucket_id: []])
end
Update:
Ok after some research, it looks like it should be bucket_ids, but the bucket_ids should be allowed as attribute for expertise. Check this post and tweak your form and expertise_params accordingly. You won't be needing accept_nested_attributes_for too!
The situation: Expertise has_many Buckets through Specialties and you want to update some bucket status of a specific expertise. So you can do this:
class ExpertisesController < ApplicationController
def your_action
#expertise = Expertise.find params[:id]
bucket_ids = params[:expertise][:specialties][:bucket_ids]
#expertise.specialties.where(id: bucket_ids).update(status: :on)
end
end

can't get through validation of nested form

I have one model Biblio and one model Authors. They are habtm in relation to each other.
Adding a new biblio, I have a nested form. I do that like so:
<%= form_for :biblio, url: administration_add_biblio_path do |f| %>
<%= f.fields_for :authors, Author.new do |aut| %>
<%= aut.hidden_field :name , :name =>"biblio[authors][1]" %>
<% end %>
This is part of the params that are sent to the controller :
"biblio"=>{"authors"=>{"1"=>{"name"=>"Vabien"}}, "title"=>"test",....
In biblios_controller, I have this :
def params_biblio
params.require(:biblio).permit(
:authors)
which has this problem: Unpermitted parameter: authors
the model Biblio looks like this:
class Biblio < ApplicationRecord
has_and_belongs_to_many :authors
validates_presence_of :authors
accepts_nested_attributes_for :authors
validates_associated :authors
and class author:
class Author < ApplicationRecord
has_and_belongs_to_many :biblios
validates :given_name, presence: true
validates :name, presence: true
The problem is that this validation of author always fails. I guess this is due to the fact that [:author][:name]is passed to Author model - but I'm not sure that that's the problem and if so how to solve it.
I should add that the biblio can have a whole bunch of authors, but only the presence of author["1"] needs to be validated.
Nested strong parameters are a bit tricky in this sense. You have to define your nested parameters to make this work. So try this:
params.require(:biblio).permit(authors: :name)
Or with other params:
params.require(:biblio).permit(:title, authors: :name)
I think the problem is the "1" key in your object being passed back to the controller. Would it make more sense to pass the authors back as an array rather than an object.
"biblio"=>{"authors"=>[{"name"=>"Vabien"}], "title"=>"test",....

Rails 3, many-to-many form using accepts_nested_attributes_for, how do I set up correctly?

I have a many-to-many relationship between Recipes and Ingredients. I am trying to build a form that allows me to add an ingredient to a recipe.
(Variants of this question have been asked repeatedly, I have spent hours on this, but am fundamentally confused by what accepts_nested_attributes_for does.)
Before you get scared by all the code below I hope you'll see it's really a basic question. Here are the non-scary details...
Errors
When I display a form to create a recipe, I am getting the error "uninitialized constant Recipe::IngredientsRecipe", pointing to a line in my form partial
18: <%= f.fields_for :ingredients do |i| %>
If I change this line to make "ingredients" singular
<%= f.fields_for :ingredient do |i| %>
then the form displays, but when I save I get a mass assignment error Can't mass-assign protected attributes: ingredient.
Models (in 3 files, named accordingly)
class Recipe < ActiveRecord::Base
attr_accessible :name, :ingredient_id
has_many :ingredients, :through => :ingredients_recipes
has_many :ingredients_recipes
accepts_nested_attributes_for :ingredients
accepts_nested_attributes_for :ingredients_recipes
end
class Ingredient < ActiveRecord::Base
attr_accessible :name, :recipe_id
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
accepts_nested_attributes_for :recipes
accepts_nested_attributes_for :ingredients_recipes
end
class IngredientsRecipes < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
attr_accessible :ingredient_id, :recipe_id
accepts_nested_attributes_for :recipes
accepts_nested_attributes_for :ingredients
end
Controllers
As RESTful resources generated by rails generate scaffold
And, because the plural of "recipe" is irregular, inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'recipe', 'recipes'
end
View (recipes/_form.html.erb)
<%= form_for(#recipe) do |f| %>
<div class="field">
<%= f.label :name, "Recipe" %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :ingredients do |i| %>
<div class="field">
<%= i.label :name, "Ingredient" %><br />
<%= i.collection_select :ingredient_id, Ingredient.all, :id, :name %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Environment
Rails 3.2.9
ruby 1.9.3
Some things tried
If I change the view f.fields_for :ingredient then the form loads (it finds Recipe::IngredientRecipe correctly, but then when I save, I get a mass-assignment error as noted above. Here's the log
Started POST "/recipes" for 127.0.0.1 at 2012-11-20 16:50:37 -0500
Processing by RecipesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/fMS6ua0atk7qcXwGy7NHQtuOnJqDzoW5P3uN9oHWT4=", "recipe"=>{"name"=>"Stewed Tomatoes", "ingredient"=>{"ingredient_id"=>"1"}}, "commit"=>"Create Recipe"}
Completed 500 Internal Server Error in 2ms
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: ingredient):
app/controllers/recipes_controller.rb:43:in `new'
app/controllers/recipes_controller.rb:43:in `create'
and the failing lines in the controller is simply
#recipe = Recipe.new(params[:recipe])
So the params being passed, including the nested attributes, are incorrect in some way. But I have tried lots of variants that fix-one-break-another. What am I failing to understand?
Thanks to clues from all, I have found what was wrong with my approach. Here's how I solved it.
I had originally tried with a simple HABTM many-to-many relationship, where the join table was named following standard Rails convention: ingredients_recipes. Then I realized that in a way, accepts_nested_attributes_for is designed for a 1-to-many relationship. So I converted to using has_many_through, creating a model IngredientsRecipes.
That name was the core problem, because Rails needs to be able to convert from plural to singular when using build to create form elements. This caused it to look for the non-existant class Recipe::IngredientsRecipe. When I changed my form so it used fields_for :ingredient the form displayed, but still failed to save with a mass assignment error. It even failed when I added :ingredients_attributes to attr_accessible. It still failed when I added #recipe.ingredients.build to RecipesController#new.
Changing the model to a singular form was the final key to resolve the problem. IngredientsRecipe would have worked, but I chose RecipeIngredients, as it makes more sense.
So to summarize:
can't use accepts_nested_attributes_for with has_and_belongs_to_many; need has_many with through option. (Thanks #kien_thanh)
adding accepts_nested_attributes_for creates a accessor that must be added to attr_accessible in the form <plural-foreign-model>_attributes, e.g. in Recipe I added attr_accessible :name, :ingredients_attributes (Thanks #beerlington)
before displaying the form in the new method of the controller, must call build on the foreign model after creating a new instance, as in 3.times { #recipe.ingredients.build }. This results in HTML having names like recipe[ingredients_attributes][0][name] (Thanks #bravenewweb)
join model must be singular, as with all models. (All me :-).
If you inspect the form that is generated, you'll notice that the nested fields have a name like "ingredients_attributes". The reason you're getting the mass-assignment error is because you need to add these fields to the attr_accessible declaration.
Something like this should fix it (you'll need to doublecheck the field names):
class Recipe < ActiveRecord::Base
attr_accessible :name, :ingredients_attributes
#...
end
Update: There's a similar answer here
Leave the call as
<%= f.fields_for :ingredients do |i| %>
But before that do
<% #recipe.ingredients.build %>
Im guessing that will allow your form to be created the right way, but there are likely other errors with your models, I can look # it more in detail when I have more time if its still not working, but:
As far as what accepts_nested_attributes_for does, when you pass in a correctly formatted params hash to the Model.new or Model.create or Model.update, it allows those attributes on the related model to be saved if they are in the params hash. In addition though, you do need to make the attributes accessible if they are unaccessible in the parent model as stated by beerlington.
I think you just need set up a one-to-many association, one recipe has many ingredients and one ingredient belongs to one recipe, so your model look like:
class Recipe < ActiveRecord::Base
attr_accessible :name, :ingredients_attributes
has_many :ingredients
accepts_nested_attributes_for :ingredients
end
class Ingredient < ActiveRecord::Base
attr_accessible :name, :recipe_id
belongs_to :recipe
end
You are built right form, so I don't write it again here. Now in your new and create controller will be like this:
def new
#recipe = Recipe.new
# This is create just one select field on form
#recipe.ingredients.build
# Create two select field on form
2.times { #recipe.ingredients.build }
# If you keep code above for new method, now you create 3 select field
end
def create
#recipe = Recipe.new(params[:recipe])
if #recipe.save
...
else
...
end
end
How does params[:recipe] look like? If you just have one select field, maybe like this:
params = { recipe: { name: "Stewed Tomatoes", ingredients_attributes: [ { id: 1 } ] } }
If you have 2 ingredient select field:
params = { recipe: { name: "Stewed Tomatoes", ingredients_attributes: [ { id: 1 }, { id: 2 } ] } }

Accepting nested attributes on a belongs_to association

I have a complex form for scheduling events. Here are the abbreviated associations:
class Event < ActiveRecord::Base
belongs_to :client
accepts_nested_attributes_for :client, :reject_if => lambda { |a| a[:name].blank? }
end
class Client < ActiveRecord::Base
has_many :events
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }
end
The form is creating a new event and I have the following structure:
- form_for #event do |event_form|
%select=collection_select(client_options_for_select, :options, :group_name, :id, :name, #event.client_id)
- event_form.fields_for :client do |client|
= client.text_field :name
- client.fields_for :questions do |question|
= question.text_field :content
The client already exists and is chosen from a select menu. An observer renders the nested attributes form by setting the client variable in a controller action and then rendering the partial.
Here is the error I'm getting:
ActionView::TemplateError (wrong number of arguments (0 for 1)) on line #1 of app/views/proceedings/_questions.html.haml:
1: - event_form.fields_for :client do |client|
app/views/proceedings/_questions.html.haml:1:in `form'
app/views/proceedings/_questions.html.haml:1:in `_run_haml_app47views47events47_client_questions46html46haml_locals_client_questions_object'
haml (3.0.21) rails/./lib/haml/helpers/action_view_mods.rb:13:in `render'
app/controllers/proceedings_controller.rb:261:in `__instance_exec0'
app/controllers/proceedings_controller.rb:260:in `corp_client_questions'
app/controllers/proceedings_controller.rb:258:in `corp_client_questions'
I'm having problems (I think) with the belongs_to association between Event and Client. I don't know if Event can accept nested attributes of Client when the Event belongs_to the Client. I've always done it the other way around (Client accepts nested attributes of Event).
Any ideas? I can elaborate if you need more code or background. Thanks!
Update: Added controller code as requested.
def client_questions
if params[:client_id].blank?
render_no_client_questions
elsif #client = Client.find(params[:client_id]) and #client.is_unspecified?
render_no_client_questions
else
respond_to do |format|
format.js {
render :update do |page|
page[:client_questions].replace_html :partial => 'client_questions', :layout => false
end
}
end
end
end
try adding an instance of the fields_for object in the options... generally a symbol isn't enough when creating a new top-level form object... Try the following, but yes it is possible to accept nested attributes on a belongs_to.
<%= event_form.fields_for :client, #client do |client| %>
<%= client.text_field :name %>
<%= client.fields_for :questions, Question.new do |question| %>
<%= question.text_field :content %>
<% end %>
<% end %>
I had the same issue using accepts_nested_attributes_for :address on a belongs_to :address association for my Order object.
The field_for wasn't echoing nothing, but all it took was adding
#order.build_address()
and that made it work.
I think is because we are using the association sort of reversed from the usual, so you have to manually create the association.
In your controller method(s), you need to add:
#event.build_client
The form cannot display fields_for when it does not have a valid object. Most of the time, we use something like #event.client.build, but this will not work with a belongs_to association. That method is only valid with has_many and has_and_belongs_to_many.
Reference here.

Resources