Question

I'm still pretty new to Rails so I could be missing some pretty major here and that's easy to fix or maybe a piece that I just haven't studied yet.

I'm creating a tour in regular form. The form has many fields but the one in question and where I'm having issues is with my collection_select. What I'm trying to do is display the tours associated to that city within the cities pages.

Here's the error that I'm getting which appears after I save the tour.

City(#70179438153960) expected, got String(#70179401165880)

models/city.rb

class City < ActiveRecord::Base
    has_many :cities
end

models/tour.rb

class Tour < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
end

I have separate controllers for cities and tours. Pretty basic scaffolding although I did add :city to the params.require(:tour).permit(.

views/tours/_form.html.erb

  <%= simple_form_for(@tour) do |f| %>

    <div class="inputs">
        <%= f.input :company, label: "Company", input_html: { class: 'form-control' } %>
...
       <%= collection_select :tour, :city, City.all, :id, :city, {:include_blank => true } %>
    </div>

...
  <% end %>

The form displays all the cities perfectly fine but updating the tour with a city gives me that error I showed up.

As an extra question for later, I'd then like to display all the tours associated to the city. For example visiting city/1 would shows the tours for that city.

Thanks!

Was it helpful?

Solution

<%= collection_select :tour, :city, City.all, :id, :city, {:include_blank => true } %>

Is :city here a string? Also the City has_many :cities relationship seems odd.

Also, if I am understanding the intent here (seems like concert tours?) then a many to many relationship might be more appropriate using a join table (:id, :user_id, :city_id) and making a has_many_through relationship.

OTHER TIPS

You can try this:

<%= f.select :tour, City.all.map{|c| [c.city, c.id] }, {include_blank: true} %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top