Tim
Tim

Reputation: 3221

Using collection_select in Rails form?

I need a multiple selection choice in a Rails form to create a new Topic, when creating a new Topic users can select a Language from the drop-down menu.

Topic.rb

class Topic < ActiveRecord::Base
  has_one :language
end

language.rb

class Language < ActiveRecord::Base
  belongs_to :topic
end

How would I use the collection_select method to have a user select a language?

The topic DB has a language field.

The language DB has a name field which I want to display to the user and a permalink field which I want to be the value of the dropdown that is stored in the topic db.

Upvotes: 0

Views: 176

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Collection Select

My understanding is that collection_select is not dependent on your associations

According to the Rails Documentation, and based off our own experience, the collection_select functionality can work with "pure" data, like this:

<%= subscriber.collection_select(:subscriber_id, Subscriber.where(:user_id => current_user.id), :id, :name_with_email, include_blank: 'Subscribers') %>

Selecting A Language

In your case, there are several issues which need to be addressed

Firstly, your foreign_key needs to be corrected in the topic database:

The topic DB has a language field

Your topic DB needs to reference langugage_id, like this:

id | language_id | created_at | updated_at

Once this has been done, it means you can populate the topics db with the language_id required to make to make the relation work. I'd use this collection_select for this:

<%= form_for @topic do |f| %>
    <%= f.collection_select(:langauge_id, Language.all, :id, :name, include_blank: 'Languages') %>
<% end %>

Upvotes: 0

nickcen
nickcen

Reputation: 1692

collection_select(:topic, :language_id, Language.all, :permalink, :name)

Upvotes: 0

Related Questions