user5853457
user5853457

Reputation:

undefined method `to_model' ActiveRecord Relation

I have this exact error message: undefined method to_model' for #<Onduleur::ActiveRecord_Relation:0x007f8bcf631110>

I am missing something...but what ? Thanks for your help :)

This is a search form in views/installations/_form.html.erb

<%= simple_form_for :query, url: @onduleurs, method: :get, wrapper: :inline_form, html: {class: 'form-inline'} do |f| %>
  <%= f.input :identifier, collection: Onduleur.group(:identifier).map {|o| o.identifier} ,  prompt: "Choississez un onduleur" %>
  <%= f.button :submit, "Chercher", class:"btn btn-success" %>
  <%= link_to "Voir tous les onduleurs", {controller: "installations", action: 'show'}, class: "btn btn-success"  %>
<% end %>

Here is my installations_controller.rb

 class InstallationsController < ApplicationController

  def index
    @installations = Installation.all
  end

  def show
    filter_onduleurs if params[:query].present?
    @onduleurs ||= Onduleur.all
    @installation = Installation.find(params[:id])
  end

  def new
    @installation = Installation.new
  end

  def create
    @installation = Installation.new(installation_params)
    if @installation.save
      redirect_to installations_path, notice: "L'installation a bien été crée"
    else
      render :new, notice: "L'installation n'a pas pu être crée, veuillez rééssayer"
    end
  end


  private

  def filter_onduleurs
    @onduleurs = Onduleur.where('identifier LIKE ?', params[:query][:identifier]) if params[:query][:identifier].present?
    @onduleurs = Onduleur.where('datetime LIKE ?', params[:query][:datetime]) if params[:query][:datetime].present?
  end

  def installation_params
    params.require(:installation).permit(:name)
  end
end

About my models:

installation.rb

has_many :onduleurs,  dependent: :destroy

onduleur.rb

belongs_to :installation

Here are my routes:

 resources :installations do
  resources :onduleurs do
    collection {post :import}
  end
end
root to: "installations#index"

Upvotes: 0

Views: 3839

Answers (1)

Gerry
Gerry

Reputation: 10497

Thats because to_model method can only be called on a single AR instance.

You are providing a collection in your form with url: @onduleurs instead of single instance of the Onduleur model.

Upvotes: 5

Related Questions