Rail associations and forms

I have a model called appointment. Everyone appointmenthas stylist. In the form where I create a new one appointment, I do this:

  <div class="field">
    <%= f.label :stylist_id %><br />
    <%= f.select(:stylist_id, Stylist.order("name").map { |s| [s.name, s.id] }) %>
  </div>

This works, but it will be tedious to do such things for every association in my application. I believe Rails has a way to automatically generate fields for associations, but I have no idea how this works. Is there such a thing?

Oh, and by the way, I already know about forests. If scaffolding needs to take care of what I describe above, I apparently am doing something wrong, because it does not for me.

(I'm on Rails 3.)

+5
source share
3 answers

, , collection_select :

<%= f.collection_select :stylist_id, Stylist.all, :id, :name %>
+23

RobinBrouwer , , :

# config/initializers/to_options.rb
module ActiveRecord
  class Base
    def self.to_options(title=:name)
      self.all.map{|r| [r.send(title), r.id]}
    end
  end
end

to_options ( name).

Model.to_options # => Creates select options with [m.name, m.id]
AnotherModel.to_options(:title) # => Creates select options with [m.title, m.id]

.

+4

, Rails select. , formtastic (https://github.com/justinfrench/formtastic) simple_form (https://github.com/plataformatec/simple_form), . simple_form , .

- , . Stylist.order... :

# Model
def self.select
  Stylist.order("name").map { |s| [s.name, s.id] }
end

# Form
<%= f.select(:stylist_id, Stylist.select) %>

.:)

+1
source

All Articles