Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Where to put errors and validations.
2 Posts
Where to put errors and validations.


I Would like discuss what is the best pratice on update validations of an object, given the update of object depends on another object.

I have this classes.

class Book < ActiveRecord::Base

 belongs_to :author, :class_name => "User", :foreign_key => "author_id"


class User < ActiveRecord::Base

 has_many :books, :foreign_key => 'author_id'


The book author only can edit/destroy the book on the first 15 minutes.

How i would make this?

create two methods on Book: - one that checks if the book is editable (don't passed the 15 minutes) - one that check if the book is changeable by the user.

and i could make a validation call back before_update to check this conditions and generate the error messages.

But my doubt is on controller side.

How it would be the best way to do this?

I came in this solution:

class BooksController < ApplicationController

  before_filter :check_editability, :only => [:edit,:update]
  def check_editability
     @book = Book.find(params[:id])
     @user = User.find(session[:user])
     if @book.editable?
       flash[:error] = "Time for delete exceeded!"
     if @book.changeable_for?(@user)
       flash[:error] = "You don't have permission to do this."
     unless flash[:error].empty?
       redirect_to(book_path(@book)) and return.


But i think is more clearer just one method like 'valid_for_update?(user)' that check these conditions and returns in form of Errors object.

What you guys think about it?

(Sorry if i ain't describe it clear enough, english is not my native language)

Best practice is to use a gem which is adding easy authorization for models, controllers and views, like: "CanCan":http://github.com/ryanb/cancan by Ryan Bates (railscasts.com creator).

2 Posts
Login to add your message