Question: Why does my associated object not save?

Question

Why does my associated object not save?

Answers 2
Added at 2017-11-30 18:11
Tags
Question

(Rails Newbie here) I have two models Usuario and Ficha. Usuario has a has_one association with Ficha.

Here are my models:

class Ficha < ApplicationRecord
 belongs_to :user
 belongs_to :usuario
end

class Usuario < ApplicationRecord
 belongs_to :user
 has_one :ficha, :dependent => :destroy
end

Here is the Usuario Controller:

    class UsuariosController < ApplicationController
      before_action :authenticate_user!
      def index
        @usuarios = Usuario.all
        @usuario_last = Usuario.last(10)
        @usuario_rev = @usuario_last.reverse
        @user_count = current_user.usuarios

        #Search
        @usuario_search = if params[:term]
          Usuario.where("name ~* ?", params[:term])
        else
          Usuario.all
        end
        @usuario_pag = @usuario_search.paginate(:page => params[:page], :per_page => 10)
      end

      def show
        @usuario = Usuario.find(params[:id])
      end

      def new
        @usuario = current_user.usuarios.build
      end

      def create
        @usuario = current_user.usuarios.build(usuario_params)

        @usuario.save
        redirect_to @usuario
      end

      def edit
        @usuario = Usuario.find(params[:id])
      end

      def update
        @usuario = Usuario.find(params[:id])

        if @usuario.update(usuario_params)
          redirect_to @usuario
        else
          render 'edit'
        end
      end

      def destroy
        @usuario = Usuario.find(params[:id])
        @usuario.destroy

      redirect_to usuarios_path
      end

      private
        def usuario_params
          params.require(:usuario).permit(:name, :age, :doc, :docnum, :estadocivil, :country, :street,
          :direction, :municipal, :zipcode, :tel1, :tel2)
        end
    end

Here is my Ficha Controller:

    class FichasController < ApplicationController
      before_action :authenticate_user!
      def index
      end

      def show
        @ficha = Ficha.find(params[:id])
      end

      def new
        @usuario = Usuario.find(params[:usuario_id])
        if @usuario.ficha.nil?
          @ficha = @usuario.build_ficha
        else
          flash[:error] = "Ya tienes una ficha"
        end
      end

      def create
        @usuario = Usuario.find(params[:usuario_id])

        @ficha = @usuario.build_ficha(ficha_params)
        if @ficha.save
          redirect_to @usuario, :notice => "Your ficha has been successfully created."
        else
          render :action => 'new'
        end
      end

      def edit
        #@ficha = Ficha.find(params[:id])
      end

      def update
        @ficha = Ficha.find(params[:id])

            if @ficha.update(ficha_params)
                redirect_to @ficha
            else
                render 'edit'
            end
      end

      def destroy

        @usuario = Usuario.find(params[:usuario])
        @ficha = @usuario.fichas.find(params[:id])
        @ficha.destroy

      redirect_to fichas_path
    end

    private
      def ficha_params
        params.require(:ficha).permit(:name, :age, :doc, :docnum, :estadocivil, :country, :street,
        :direction, :municipal, :zipcode, :tel1, :tel2, :time, :redes, :estudios, :profession,
        :laboral, :discapacity, :percent, :derivado1, :derivado2, :derivacion, :nombredelprofesional,
        :observaciones, :conocio, :signature, :date, :term)
      end
    end

Am I going wrong somewhere with the creation of the ficha in the controller? Would it be better to create the object right after with after_create in the usuario model?

Any help is appreciated! Thanks!

Answers to

Why does my associated object not save?

nr: #1 dodano: 2017-11-30 18:11

Yes, you're going about this the right way. If your @ficha object isn't saving, it's likely because of validation errors, or not being associated properly.

Check out debugging with the console command to learn how you can troubleshoot these types of problems, by inserting a console after your save attempt to see if there are any errors attached to your @ficha object.

Web Console is a bit like byebug, but it runs in the browser. In any page you are developing, you can request a console in the context of a view or a controller. The console would be rendered next to your HTML content. 4.1 Console

Inside any controller action or view, you can invoke the console by calling the console method.

nr: #2 dodano: 2017-12-01 06:12

In Rails 4.2.1

Here i don't see that you use 'accepts_nested_attributes_for'. Read about that http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Try these

class Ficha < ApplicationRecord
 belongs_to :user
 belongs_to :usuario
end

class Usuario < ApplicationRecord
 belongs_to :user
 has_one :ficha, :dependent => :destroy
 accepts_nested_attributes_for :ficha
end

and also you have permit ficha_attributs in UsuariosController like these

private
  def usuario_params
     params.require(:usuario).permit(:name, :age, :doc, :docnum, :estadocivil, :country, :street,:direction, :municipal, :zipcode, :tel1, :tel2, ficha_attributes: [# Write ficha attributes you want save])
  end
Source Show
◀ Wstecz