I have the following form:
<%= form_for @user, :html => {:class => 'edit-form' }, :url => {:action => 'add_group', :id => @user.id }, :remote => true do |f| %>
<%= f.select :group_ids, Group.all.collect {|x| [x.name, x.id]}, {}, :class => 'multiselect', :multiple => true %>
<button type="submit" id="submit_it" class="btn btn-primary">Submit</button>
<% end %>
And in my controller:
def add_group
@user = User.find(params[:id])
unless @user.update_attributes(option_params)
respond_to do |format|
format.html
format.js
end
end
end
def option_params
params.require(:user).permit!
end
And thus, when the form is submitted, I do get a response with my "update.js.erb" file, and the following shows up in the console:
Started PATCH "/user_management/add_group?id=41" for 123.45.67.89 at 2014-07-07 22:58:38 +0000
Processing by UserController#update as JS
Parameters: {"utf8"=>"✓", "user"=>{"group_ids"=>["", "3", "4"]}, "multiselect"=>"4", "id"=>"add_group"}
Rendered user/update.js.erb (0.1ms)
Completed 200 OK in 13ms (Views: 11.9ms | ActiveRecord: 0.0ms)
But, nothing actually gets updated in the database.
There are no validations in my model that would be causing this not to update.
My model relationships are such:
class User < ActiveRecord::Base
has_many :group_assignments
has_many :groups, through: :group_assignments
end
class Group < ActiveRecord::Base
has_many :group_assignments
has_many :users, through: :group_assignments
end
class GroupAssignment < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
Any ideas on why this would not be updating?
I thought it might be because the form is loaded via AJAX and there is no CSRF tags. So I added <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
to the form. Now, the authenticity token is in the params.
And thus, when the form is submitted, I do get a response with my "update.js.erb" file, and the following shows up in the console... But, nothing actually gets updated in the database.
Well, yes. Your code says, "unless the attributes are updated successfully, respond to html and js." And since the attributes aren't updated, it renders the template that corresponds to the request format. (For this reason, I try to use if
as much as possible, instead of unless
. It makes the code easier to read and understand.)
One method you can use to get more information is to change the method to update_attributes!
. This will make it so that, instead of simply returning false, the method will raise an exception if the record is invalid for some reason.
As a side note, you should avoid using permit!
. The entire point of strong parameters is that you make conscious decisions about which attributes to allow.