Reputation: 15
I am new to Rails and I have these checkboxes that display the options just fine, but aren't changing anything in the database as the form is submitted. The form in views has the following piece of code:
<%= form_for(@sector) do |f| %>
<%= f.collection_check_boxes :admins_id, Admin.all, :id, :name %>
<% end %>
and this is the corresponding action in the sectors controller:
def update
@sector = Sector.find(params[:id])
@sector.admins_id = params[:admins_id]
respond_to do |format|
if @sector.update(sector_params)
format.html { redirect_to @sector, notice: 'Sector was successfully updated.' }
format.json { render :show, status: :ok, location: @sector }
else
format.html { render :edit }
format.json { render json: @sector.errors, status: :unprocessable_entity }
end
end
end
private
def sector_params
params.require(:sector).permit(:title, :admins_id)
end
And, finally, I have these relations in the models:
class Sector < ActiveRecord::Base
has_many :admins, dependent: :destroy
validates :title, presence: true
validates :title, uniqueness: true
end
class Admin < ActiveRecord::Base
belongs_to :sector
end
Also, I can create and assign admins just fine in the rails console.
Upvotes: 0
Views: 346
Reputation: 2986
If you are setting a single admins_id then you don't need check boxes (which will pass through an array of ids) use collection_radio_buttons (for a single id) instead.
However, if you want to set multiple admins through the has_many association, then keep the checkboxes, but change the attribute name to be admin_ids. (Don't forget to change the name in the permit() whitelist as well).
Also, you can remove this line:
@sector.admins_id = params[:admins_id]
It's not necessary because it is set through the update().
Upvotes: 1