I just wrote my first ruby on rails application and I'm kinda stuck. I have a library database with authors, books and categories. a book belong to an author and category. SO now when creating a book I would like to select an author and category from a list. How do I go about doing that. I'm new on ruby so any help would be appreciated. For now the book only has the name column.
Here is the books class or model:
class Book < ActiveRecord::Base
belongs_to :author
belongs_to :category
attr_accessible :name
validates :name, :presence => true
end
In your books form use following select field as:
<%= f.select :author_id, Author.all.collect {|p| [ p.name, p.id ] } %>
<%= f.select :category_id, Category.all.collect {|p| [ p.name, p.id ] } %>
For more details of association alse see http://guides.rubyonrails.org/association_basics.html
It likely be something like in your view:
<% form_for :book do |f|%>
<% f.text_field :name %>
<% f.select :author_id, options_for_select( @authors.all.map{|a| a.name, a.id } %>
<% f.select :category_id, options_for_select( @categories.all.map{|c| c.name, c.id} ) %>
<% end %>
and something like
@authors = Author.all
@categories = Category.all
in your controller
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.