0 votes

Error in the creation of new posts in rails

I am creating a rails application in which a freelancer has a has_one association with a service. the app is running fine until a new service must be created as a freelancer. when creating a new post I get the error.

I did a test leaving the freelancer association with has_many and it works perfect leaving current_freelancer.services.build. but with has_one I get the error mentioned above.

NoMethodError in ServicesController#new undefined method `services' for # Did you mean? service service=

the controller for the services is as follows.

class ServicesController < ApplicationController
  before_action :set_service, only: [:show, :edit, :update, :destroy]

  def index
    @services = Service.all
  end

  def show
  end

  def new
    @service = current_freelance.services.build
  end

  def edit
  end

  def create
    @service = current_freelance.services.build(service_params)

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

2voto

Alter Lagos Points 2290

The error itself is telling you the answer: Did you mean? service .
If you are using a relationship has_one should be in the singular service but if it is with has_many it is necessary to use plural services . Convention on configuration.
Greetings

0voto

mariovzc Points 682

I did a test by leaving the freelancer association with has_many and works perfect leaving current_freelancer.services.build. but with has_one I get the error mentioned above.

Here is your mistake when the relationship is has_one service should be in singular you should replace current_freelance.services.build by current_freelance.service.build

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X