AleA
AleA

Reputation: 17

Rails 5: nested resources undefined method _path

I have three tables: users, observative_sessions and observations.

In each respective model there's

users.rb

has_many :observative_sessions, dependent: :destroy
has_many :observations, through: :observative_sessions, dependent: :destroy

observative_sessions.rb

belongs_to :user
has_many :observations, dependent: :destroy

observations.rb

belongs_to :observative_session
belongs_to :user

In routes.rb I nested observations in observative_sessions

resources :observative_sessions do
  resources :observations
end

I show the list of possible observations for each observative_session so I created the partial (observations/_index.html.erb) to render in the show page of observative session.

<%= render 'observations/index' %>

and a button to create new observations

<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#new-observation-modal">Create</button>

observative_sessions_controller.rb

def show
   @q = Observation.ransack([:observative_session])
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) if params[:q].present?
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) unless params[:q].present?
   @observation = Observation.new
end

Now I have a problem, when I try to create a new observation the button calls the new_modal which renders the form

<%= render 'observations/form' %>

observations/_form.html.erb

<%= bootstrap_form_for ([@observative_session, @observation]) do |f| %>

And here I get the error Undefined method 'observations_path' This is how I defined the creation method in observations_controller.rb

def create
  @observation = Observation.new(observation_params)

respond_to do |format|
  if @observation.save
    format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
    format.json { render :show, status: :created, location: @observation }
  else
    format.html { render :new }
    format.json { render json: @observation.errors, status: :unprocessable_entity }
  end
end

end

Thank you so much for any help.

Upvotes: 0

Views: 253

Answers (1)

AleA
AleA

Reputation: 17

My bad the error was on new.html.erb I passed

<%= render 'form', observation: @observation %>

instead of

<%= render 'form', observation: ([@observative_session, @observation]) %>

and in observations_controller.rb I had to add

    @observative_session = ObservativeSession.find(params[:observative_session_id])
    @observation = @observative_session.observations.build(observation_params)

By the way before I was trying to use thinking of passing the id of the session

ObservativeSession.find(params[:id]) 

instead it should be

ObservativeSession.find(params[:observative_session_id]) 

Upvotes: 1

Related Questions