Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practices of Rails

I'm looking for people's examples of good* practices when using Rails.

I've got a couple such as:

  • before_filter calls go underneath the controller class name declaration, nowhere else.
  • Base controllers for a namespace are named BaseController, not ApplicationController. There is, and should forever be, only one ApplicationController.
  • attr_* methods are defined at the top of their respective classes.
  • Model callbacks go after attr_* methods, or at the top of the model.
  • Validations go at the top of the model, with custom validation methods being defined as private methods at the bottom of the file.

Now I'm not looking for Ruby's good practices, but more of a list of ones specifically in Rails. The ones listed above are just an example, not gospel.

* I didn't want to use the term "best practices", as best implies an ultimate, and in all things code people may disagree.

like image 200
Ryan Bigg Avatar asked Jan 24 '11 23:01

Ryan Bigg


2 Answers

One practice I've found to be pretty consistent is when parentheses are appropriate. DSL class macros like validations and associations seem natural without them, whereas methods with an explicit receiver and argument(s) seem better with them.

has_many :users

User.find_all_by_field(my_var)

vs

has_many(:users)

User.find_all_by_field my_var
like image 95
Peter Brown Avatar answered Oct 09 '22 16:10

Peter Brown


  1. I put attr_accessible* after the has_* declaration.
    I do remember getting errors if I did not declare them in the above order. (I'll recreate this problem tomorrow and reconfirm)

    Tried it out:

    Works:

    has_one :something
    accepts_nested_attributes_for :something
    

    But this throws error:
    No association found for name 'something'. Has it been defined yet?:

    accepts_nested_attributes_for :something
    has_one :something
    

    I think, the reason I get this error is because I am using something in a scope before the has_one call.

  2. If you do @posts.something and get nil errors in a (say, index) view but you know the @posts = Post.find in the index action is working, make doubly sure you do not have another (most likely empty) def index somewhere (most likely lower down) in the controller class code!

like image 34
Zabba Avatar answered Oct 09 '22 16:10

Zabba