I’ve setup two models, 1 and 2, that are associated by
has_and_belongs_to_many. I’m trying to get an attribute from model_1 to
use
in a method in model_2. When I use the code below, I get an error saying
‘undefined method model_1_id’. What am I missing? Thanks!
Model_2.rb
Class Model_2 < ActiveRecord::Base
…
has_and_belongs_to_many :model_1
def some_method
attr_a * Model_1.find(model_1_id).attr_I_need
end
Well that’s kind of what I need help with, I’m not sure where it needs
to be defined in a many-to-many relationship. I’ve already created the
join table that contains both ids.
Well that’s kind of what I need help with, I’m not sure where it needs
to be defined in a many-to-many relationship. I’ve already created the
join table that contains both ids.
The point is that your example makes no sense; you’ve defined this
as a “to-many” relationship – which Model_1 are you looking for?
Well that’s kind of what I need help with, I’m not sure where it needs
to be defined in a many-to-many relationship. I’ve already created the
join table that contains both ids.
The point is that your example makes no sense; you’ve defined this
as a “to-many” relationship – which Model_1 are you looking for?
Sorry, I should clarify. In my Model_2 view, I’m trying to simply have a
table that iterates through all the model_1’s and calculates that method
above using the model_1’s attribute that I need
Sorry, I should clarify. In my Model_2 view, I’m trying to simply have a
table that iterates through all the model_1’s and calculates that method
above using the model_1’s attribute that I need
But you’re not showing us a view, you’re showing us a model.
Do you really want some_method to return one value or an array
of values?
If you only want one value, why don’t you pass the Model_1 instance
(or the attribute) you’re interested in to the Model_2 instance?
def some_method(model_1_attribute)
attr_a * model_1_attribute
end