Home > Software engineering >  NoMethodError | nested routes path problem in rails 6
NoMethodError | nested routes path problem in rails 6

Time:07-11

I haven't been able to solve the error for a couple of days because of the nested path, what is the problem?

log error

I realize that there is no such nested path as Rails is looking for, but why is he looking for it?

routes.rb:

  resources :films do
    resources :reviews, except: %i[new show]
  end

ReviewsController:

class ReviewsController < ApplicationController
  include FilmsOpinions
  before_action :set_film
  before_action :authenticate_user!

  def create
    @review = @film.reviews.build review_create_params

    if @review.save
      flash[:success] = t 'contacts.create.success'
      redirect_to film_path(@film)
    else
      load_film_reviews(do_render: true)
    end
  end

  private

  def review_create_params
    params.require(:review).permit(:title, :desc).merge(user: current_user)
  end

  def set_film
    @film = Film.find params[:film_id]
  end

end

reviews/_form:

= render 'shared/errors', object: @review

= form_with model: [@film, @review] do |f|
  .form-group
    label.input-label.text-white  = t(".title")
    = f.text_field :title, class: "form-control"

  .form-group
    label.input-label.text-white = t(".please_add_your_reviews")
    = f.text_area :desc, class: "form-control rounded-0"

  .btn-primary
    = f.submit t("submit")

and my render in films/show

= render 'reviews/form'

At first glance, the basic things that I have already done, but now for some reason I encounter an error

CodePudding user response:

The following line may be the culprit:

= form_with model: [@film, @review] do |f|

See if changing the above fixes it

= form_with model: [@film, @review],
            url: @review.new_record? ? polymorphic_url([@film, :reviews]) : film_reviews_path(@film, @review))

The idea is to create the URL based on the object

If it's new - we are doing POST to create action If it already exists we are doing a PATCH to update action

CodePudding user response:

Nested path problem -

= form_with url: film_reviews_url(@film, @review) do |f|

ActionController::ParameterMissing - param is missing or the value is empty: review:

nested model problem -

= form_with scope: :review, url: film_reviews_url(@film, @review) do |f|

Thanks to the team leader for the answer. Solved problems for nested models

  • Related