0
votes

I've spent nearly all day on this particular issue and although there are other posts about it, I've not resolved my particular issue.

I've tried following RailsCast #196 but still can't identify my mistake.

MODELS:

Exercises

# == Schema Information
#
# Table name: exercises
#
#  id          :integer          not null, primary key
#  name        :string(255)
#  description :text
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  image       :string(255)
#

class Exercise < ActiveRecord::Base
  attr_accessible :description, :name, :tags_attributes
  has_many :tags
  has_one :difficulty
  accepts_nested_attributes_for :tags, :allow_destroy => true
end

Tags

# == Schema Information
#
# Table name: tags
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Tag < ActiveRecord::Base
  attr_accessible :name, :exercise_id
  belongs_to :exercise
  accepts_nested_attributes_for :exercises
end

FORM

<%= form_for(@exercise) do |f| %>
  <% if @exercise.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@exercise.errors.count, "error") %> prohibited this exercise from being saved:</h2>

      <ul>
      <% @exercise.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <%= f.fields_for :tag do |builder| %>
    <div class="field">
        <%= builder.label :name, "Tags" %><br />
        <%= builder.text_field :name %>     
    </div>
<% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

The error, specifically, when I submit the form is:

ActiveModel::MassAssignmentSecurity::Error in ExercisesController#create

Can't mass-assign protected attributes: tag

Application Trace | Framework Trace | Full Trace
app/controllers/exercises_controller.rb:42:in `new'
app/controllers/exercises_controller.rb:42:in `create'
1

1 Answers

1
votes

In your form, replace the line

<%= f.fields_for :tag do |builder| %>

with

<%= f.fields_for :tags do |builder| %>

In your model you're using attr_accessible and then you add the plural followed by _attributes so you can set the attributes, but in your form you called the singular tag hence why you're getting a mass-assign protected attributes error.