Search code examples
ruby-on-railsmodel-view-controllerruby-on-rails-4nested-resources

Form_for sub-resource throws an error


I have two models: Point and PointPage. Point has_many :point_pages and PointPage belongs_to :point.

In routes.rb

resources :points do
  resources :point_pages
end

When creating Point rails creates two PointPages, belonging to that point.

In point_pages_controller.rb

def index
  point = Point.find(params[:point_id])
  @page_from = point.point_pages.find_by(page_type_from: true)
  @page_to = point.point_pages.find_by(page_type_from: false)
end

So, I need to show both PointPages (@page_from and @page_to) for certain Point on one index page. And I need to allow users to edit these PointPages on that one page. But when I create form_for @page_from and form_for @page_to on this index page, I get an error:

undefined method `point_page_path' for #<#<Class ... >>

Thanks for any ideas!


Solution

  • You should change your action to be like this:

    def index
      @point = Point.find(params[:point_id])
      @page_from = point.point_pages.find_by(page_type_from: true)
      @page_to = point.point_pages.find_by(page_type_from: false)
    end
    

    This way you will have the @point

    And in your view you should create the forms like this:

    form_for [@point, @page_from]
    

    and

    form_for [@point, @page_to]
    

    When you have nested routes you need to adjust the form_for object to work properly. You can see more details here http://guides.rubyonrails.org/form_helpers.html