Home > Software engineering >  Rails: How to reference a path from one Model in another Models Controller?
Rails: How to reference a path from one Model in another Models Controller?

Time:11-21

This is an easy question, but I am new to Rails. Simply put, I want to use a route from another model (Score) in my Prediction controller. Once a new prediction is made, I want to redirect to the new_score_path but I keep getting an error -

 undefined local variable or method `new_scores_path' for #<PredictionsController:

I guess I need to somehow reference the Score model in the Predictions Controller but I am not sure how to do this. Here is my create method

  def create
    @prediction = Prediction.new(prediction_params)
    respond_to do |format|
      if @prediction.save
       user = User.find(@current_user.id)
       user.lastcase = user.lastcase   1
       user.save
       @user = user
       @patient = Patient.find(@current_user.lastcase)
       format.html { redirect_to url: new_scores_path, notice: 'Prediction WAS successfully created.' }
       format.json { render :new, status: :created, location: @prediction }
      else
       format.html { render :new, status: :unprocessable_entity }
       format.json { render json: @prediction.errors, status: :unprocessable_entity }
      end
   end
  end

Many thanks for reading.

EDIT

I tried

  new_score_path 

and it simply routed me to predictions (i.e. in the index.html.erb file). This was in the address bar

   http://localhost:3000/predictions?notice=Prediction WAS successfully created.&url=/scores/new

CodePudding user response:

This is an easy question, but I am new to Rails. Simply put, I want to use a route from another model (Score) in my Prediction controller.

You're thinking about it wrong. The controller doesn't belong to a model. Nor does the route. Models are just an internal implementation detail of the application (or at least they should be in the best of worlds).

All the routing helpers generated from routes.rb are available into all your controllers and views no matter what they are named.

I guess I need to somehow reference the Score model in the Predictions Controller but I am not sure how to do this.

Provided you're following the conventions and have declared the route with resources :scores you just need to call the correct helper method new_score_path. The new action route helper is always new_singular_path.

The only actual link between routes and models is that Rails provides helpers that can guess what route helper to use based on the name of a model and the Rails conventions.

CodePudding user response:

After reviewing the documentation, I explicitly gave the path

 redirect_to "/scores/new"

This solved the problem; I am unsure if this is the correct/good way to do this, but it worked. Happy to be schooled on better solutions if there are any.

  • Related