We have 3 models model1, model2, model3. This 3 are connect with
class Model1 < ActiveRecord::Base
has_many :model2s
end
class Model2 < ActiveRecord::Base
belongs_to :model1s
has_many :model3s
end
class Model3 < ActiveRecord::Base
belongs_to :model2s
end
In the table of Model1 exists id.
In the table of Model2 exists id and model1_id.
In the table of Model3 exists id and model2_id.
Now i want to get Data from the table1 and table2 out of Model3Controller.
This works fine.
class Model3Controller < ApplicationController
def create
@model2controller = Model2.find(params[:model3controller][:model2_id])
@model1controller = ?
end
end
How do we get data from the associated dataset from the table1 of the model1controller? Did we have to add the model1_id into the table3, or can we call it on an other way. Like this pseudocode
@model1controller = Model1.find(
params[:model3controller][:model2_id]params[:model2controller][:model1_id])
I might be missing something, but it looks like you should only do the following:
Edit. The above code works just like the following lines:
Please note that accessing methods on instance is done calling in lowercase, i.e.
In your example you make mistake, calling
Model3.find_by_id(params[:id]).Model2(notice the capital letter inModel2, which is wrong)Also, check if params[:id] are actually being passed to the controller action. Otherwise, if it’s absent,
Model3.find_by_id(params[:id])will returnniland thus a mentioned error will be raised.