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.BaseController
, not ApplicationController
. There is, and should forever be, only one ApplicationController
.attr_*
methods are defined at the top of their respective classes.attr_*
methods, or at the top of the model.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.
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
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With