Reputation: 1149
I created a project using nested form to add multiple options on select but is not saving correctly.
Tables:
|users|
|id| |name| |lastname|
1 Cristiano Ronaldo
2 Lionel Messi
3 David Beckham
4 Thomas Muller
|ejecutives|
|id| |name|
1 Mourinho
2 Guardiola
|user_ejecutives|
|id| |user_id| |ejecutive_id|
1 1 1
2 1 4
3 2 3
4 2 2
Controller users_controller.rb:
def new
@user = User.new
@ejecutives = Ejecutive.where('id=1')
@user_ejecutives = @user.user_ejecutives.build
end
def create
@user = User.new user_params
@user.save
end
private
def user_params
params.require(:user).permit(:name,:lastname, user_ejecutives_attributes: [])
end
Models:
#User.rb
has_many :user_ejecutives
accepts_nested_attributes_for :user_ejecutives
#Ejecutive.rb
has_many :user_ejecutives
#UserEjecutive.rb
belongs_to :user
belongs_to :ejecutive
View
<%= form_for @user do |f| %>
<%= form.text_field :name %>
<%= form.text_field :lastname %>
<%= f.fields_for :user_ejecutives do |builder| %>
<%= render 'user_ejecutive_fields', :f => builder %>
<% end %>
<% end %>
Partial:
Select user ejecutives:
<%= f.select :ejecutive_id, @ejecutives.collect { |e| [e.name,e.id] }, {prompt: "Select 2 or more"}, {:multiple => true, class: "input-lg"} %>
Here is the demo project edited:
http://code.runnable.com/VvMYsfuOOwtvL870/nested-form-listbox-multipe-options
The issue is that is not saving multiple selections:
Parameters: {"utf8"=>"✓", "user"=>{"name"=>"sddasdas", "lastname1"=>"das","user_ejecutives_attributes"=>{"0"=>{"ejecutive_id"=>["", "1", "2"] }}} , "commit"=>"Save"}
INSERT INTO `users` (`name`, `lastname1`, `created_at`, `updated_at`) VALUES ('David', 'Beckham', '2016-03-28 19:43:18', '2016-03-28 19:43:18')
INSERT INTO `user_ejecutives` (`user_id`, `created_at`, `updated_at`) VALUES (68, '2016-03-28 19:43:18', '2016-03-28 19:43:18')
COMMIT
Is not saving the name selected in mysql I see NULL
Upvotes: 0
Views: 102
Reputation: 26
params.require(:user).permit(:name, :lastname,:user_ejecutives_attributes )
Don't forget the colon (:user_ejecutives_attributes instead of user_ejecutives_attributes). It is a ruby symbol.
change in user model:
has_many :ejecutives, through: :user_ejecutives
change in ejecutives model:
has_many :users, through: :user_ejecutives
I would take collection select instead of select:
f.collection_select( :ejecutive_id, Ejecutive.all, :id, :name, {:include_blank => 'Please Select'})
Upvotes: 0
Reputation: 727
see the server console, it says
Unpermitted parameters: user_ejecutives_attributes
your users_params
in users_controller
params.require(:user).permit(:name, :lastname, user_ejecutive_ids: [] )
change user_ejecutive_ids
to user_ejecutives_attributes
may be it will works
Upvotes: 0