14

I read about collection_check_boxes but I don't understand how can I set the checked values. I have the following model:

class Objective < ActiveRecord::Base

  has_many :indicators
  has_many :objective_children, class_name: "Objective", foreign_key: "parent_id"

  def objective_ids
    objective_children.collect{|o| o.id}
  end

  def objective_ids= objectives_ids
    objectives_ids.each do |id|
      objective_children << Objective.find(id)
    end
  end
end

edit view:

<%= form_for(@objective) do |f| %>
  <%= f.collection_check_boxes :objective_ids, Objective.all, :id, :name %>
  <%= f.submit %>
<% end %>

the html checkbox are ok but I don't know how to set the values to objective. I was tried define objective_ids= objectives_ids but nothing happens.

In Controller:

class ObjectivesController < ApplicationController
    def objective_params
      params.require(:objective).permit(:name, :code, :description, :objective_ids)
    end
end

EDIT The log file says Unpermitted parameters: perspective_id, objective_ids

Cristhian Boujon
  • 4,060
  • 13
  • 51
  • 90

2 Answers2

28

I solved changing the line

params.require(:objective).permit(:name, :code, :description, :objective_ids)

to

params.require(:objective).permit(:name, :code, :description, :objective_ids => [])
Cristhian Boujon
  • 4,060
  • 13
  • 51
  • 90
  • 1
    It can also be written as `.permit(:name, :code, :description, objective_ids: [])` – user664833 Jun 10 '14 at 20:26
  • This works as long as you have :objective_ids => [] as the last element. If you put it between other symbols, you get a syntax error. Those who saw the syntax error, place it as the last element and the error will go away. – Asad Shakil Jul 01 '20 at 09:47
3

I get the same problem, try this line:

params.require(:objective).permit(:name, :code, :description, :objective_ids => [])

but does not work and i change to:

params.require(:objective).permit(:name, :code, :description, {:objective_ids => []})

and it works !!

user391990
  • 95
  • 5