Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
Hi,
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"
end
class User < ActiveRecord::Base
has_many :books, :foreign_key => 'author_id'
end
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]
private
def check_editability
@book = Book.find(params[:id])
@user = User.find(session[:user])
if @book.editable?
flash[:error] = "Time for delete exceeded!"
end
if @book.changeable_for?(@user)
flash[:error] = "You don't have permission to do this."
end
unless flash[:error].empty?
redirect_to(book_path(@book)) and return.
end
end
end
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).
