Matías Baeza Graf
Matías Baeza Graf

Reputation: 123

No method error in Pets#edit in Ruby on Rails

I have a Ruby on Rails application in which I have the following resources pets, pet types, vaccinations(the event of vaccinating a pet) and persons. So, pet belongs to a type (a type has many pets) and vaccination belongs to a pet (a pet can have many vaccinations). What I want to do is the following: To have a collapsable list (a select) o all the pet types with a submit button in the vaccinations index, so that I can filter vaccinations by pet types. My code is the following:

This is in the Pet cotroller:

def new
  @pet = Pet.new
  @sex = ["Male" , "Female"]
  @owner = Person.where(occupation: "Owner")
end

def edit
end

This in the Pet form:

<div class="field">
<%= form.label :owner %>
<%= form.collection_select(:person_id, @owner, :id, :surname) %>
</div>

<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>

<div class="field">
<%= form.label :type %>
<%= form.collection_select(:type_id, Type.all, :id, :name) %>
</div>

<div class="field">
<%= form.label :born %>
<%= form.date_select :born %>
</div>

<div class="field">
<%= form.label :sex %>
<%= form.select(:sex, @sex) %>
</div>

<div class="actions">
<%= form.submit %>
</div>
<% end %>

I don´t have any problem in creatin a pet, but when I wan to edit a pet, it gives me the no method error: enter image description here

Upvotes: 2

Views: 71

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

When you use collection_select, the collection you pass is mapped to create the options for the select is going to be built:

collection.map do |element|
  [value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
end

Right now you're not passing a collection, that's why you get the error telling you there's no method map for a nil object.

As stated in the docs, the method definition is expecting a second argument which is the collection:

collection_select(method, collection, value_method, text_method, options = {}, html_options = {})

You should pass whatever you want to create the select tag as you're doing in form.collection_select(:type_id, Type.all, :id, :name).

Upvotes: 5

Related Questions