yerassyl
yerassyl

Reputation: 3048

How to distinguish method from attribute in rails 4

I have a cartridge and dosing_edge models such that they have the relationships has_many and belongs_to respectively. By doing that I can call:

@cartridge.dosing_edges

to retrieve all dosing_edges that belong to a cartridge. And that works, but cartridge model also has a dosing_edges attribute. How do I distinguish between method and attribute.

I mean, if I want to access @cartridge.dosing_edges not to call method .dosing_edges to retrieve all dosing_edges.

Or should I rename my dosing_edges attribute to be different.

Upvotes: 0

Views: 74

Answers (3)

Max Williams
Max Williams

Reputation: 32943

@MKumar is right that you should rename your association. As some explanation, though, you can access attributes loaded from the database using the [:attname] hash-style notation (see bottom of answer)

So, when you say @cartridge.dosing_edges you're calling a method: this method will have been defined for you by default by rails to read the attribute, and you might have overwritten it with the methods added in by the has_many macro, which will add a variety of methods, including dosing_edges (assuming you haven't changed the name yet).

The default dosing_edges method would look like this:

def dosing_edges
  self[:dosing_edges]
end

self[:dosing_edges] is getting the attribute instance variable, rather than calling the method.

Upvotes: 1

rmagnum2002
rmagnum2002

Reputation: 11421

As far as I know, if you have dosing_edges attribute and dosing_edges method, when you call object.dosing_edges you'll get whatever method returns, cause having a method with the same name as attribute you basically overwrite the attribute, as the attribute of a class is a method too that can be overwritten. You could rename your has_manyrelations to something different.

Upvotes: 1

Sachin R
Sachin R

Reputation: 11876

give different name to your has_many association.

has_many :all_dosing_edges, class_name: "DosingEdge"

I think this will work for you.

Upvotes: 7

Related Questions