This project is archived and is in readonly mode.

#649 ✓stale
flip

Validation issue with HABTM

Reported by flip | July 18th, 2008 @ 12:38 AM | in 2.x

Validation of attributes by the model layer is not always possible with a HABTM relationships.

Here is a simple situation so you can understand where i'm going :

Condition Model

class Condition < ActiveRecord::Base
	has_and_belongs_to_many :departments, :order => 'numero ASC'
	
	validates_presence_of :departments	
end

Departments Model

class Department < ActiveRecord::Base
	has_and_belongs_to_many :conditions
end

Condition Controller

class ConditionController < ApplicationController
	
	def edit
		params[:condition] ||= {}
		params[:condition][:department_ids] ||= []
		
		@condition = Condition.find_by_id(params[:id])
		
		if request.post? and @condition.update_attributes(params[:condition])
			flash[:notice] = "Updated successfully"
			redirect_to :action => :list
		end
	end
end

Let's assume the tables and the join table (conditions_departments)are created.

Well the thing is : we want to ensure there is a least one department associated with a condition. On creation, there is no problem, if departments is empty the condtion object is not created

department = Department.new.save

condition = Condition.new(:department_ids => [])
condition.save
=> false
condition.departments<<department
condition.save
=>true

However on update, (with update_attributes), if the validation fails on departments the condition object is not updated, but the join table conditions_departments is updated with the invalid data.

condition.department_ids = []
condition.valid?
=>false
condition.departments.empty?
=>true

The thing is that whenever you do something like :

condition.department_ids = something
condition.departments = something

It gets saved instantly on the database, and update_attributes uses this kind of assignation method. So even if there is an error on the association it gets saved.

To ensure we don't save invalid data on the database we've got to make some validation on the contoller layer : testing directly the data or calling a validation method which ensure the data in the params hash is correct.

Ok but if we follow the MVC architecture the validation has to stay to the model layer.

If the collection of an HABTM association doesn't gets instantly saved on modifications it'd be great, and so convenient. I still don't understand why this choice of instant save has been made

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages