Assuming I am abstracting code, and am looping through the column names of object x, what’s the best way to detect if a column is an association or not?
I know I can do this, but I am wondering if there is a better way:
@user = User.first
@user.attributes.keys.each do |column|
if column[-3..-1] == "_id" && @user.respond_to?(column[0..-4].to_sym)
puts "#{column} is an association / relation."
else
puts "#{column} is not an assocation / relation."
end
end
end
Any built-in Rails methods or helpers to detect associations? Code above is neither pretty nor fool proof. Thanks!
One way to do this would be to reflect upon all associations for that class:
And then to find just the
belongs_toones, since those will have the_idfield:Then you can find the foreign key used on these associations by doing this:
I wouldn’t use
@user.attributesto get the attributes and thenkeyson that to get the column names. I would useUser.column_namesto get the column names.Therefore, with all that explained, you can then change your code to be this to make it more foolproof: