When i try to access to a method created by the relationship has_many - belogs_to, i get an undefined method error . Here is the code (semplified) :
local.rb (model) :
class Local < ActiveRecord::Base
has_many :foods, dependent: :destroy, :foreign_key => 'local_id'
end
food.rb :
class Food < ActiveRecord::Base
attr_accessible :descrizione, :nome, :prezzo, :voto
belongs_to :local, :foreign_key => 'local_id'
end
the /locals/show.html.erb view that calls the create action on foodsController :
...
<%= form_for :food, :url => {:controller => :foods, :action => :create} do |f| %>
...
<% end %>
foods_controller.rb
class FoodsController < ApplicationController
def create
@food = @local.foods.build(params[:food])
end
end
The problem is raised here in foods_controller on create action : "undefined method 'foods' ' . Why? the relationship should enable the local.foods method? (@local is defined in locals_controller.rb, @local = Local.find(params[:id]) , and local_id attribute is defined in schema.rb and in the last db migration , just to be clear)
Thank you
Since @local
is defined in a different controller, you won't be able to access it from FoodController.