我是RoR的新手,在嘗試從多個下拉列表中保存時遇到問題。我有三個對象 - 書籍,流派和作者。書對象具有與其相關的流派和作者,但問題是我只能設法將流派或作者保存到我的書對象,而不是兩者。下面是我在哪裏:Ruby on Rails下拉值不保存
class Author < ActiveRecord::Base
validates :name, :presence => true
validates :biography, :presence => true
has_many :books
end
class Genre < ActiveRecord::Base
validates :description, :presence => true
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :genre
belongs_to :author
has_many :cartitems
validates :name, :presence => true
validates :price, :presence => true
validates :description, :presence => true
end
控制器:
def create
#@book = Book.new(params[:book])
@author = Author.find(params[:author].values[0])
@genre = Genre.find(params[:genre].values[0])
@book = @author.books.create(params[:book])
#one or the other saves, but not both
#@book = @genre.books.create(params[:book])
respond_to do |format|
if @book.save
format.html { redirect_to(@book, :notice => 'Book was successfully created.') }
format.xml { render :xml => @book, :status => :created, :location => @book }
else
format.html { render :action => "new" }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity }
end
end
末
不知道這是否會助陣或沒有,但這裏的下拉菜單中是什麼樣子的視圖:
<div class="field">
<%= f.label :genre %><br />
<%= @items = Genre.find(:all)
select("genre", "description", @items.map {|u| [u.description,u.id]}, {:include_blank => true})%>
感謝任何幫助。
編輯 - 這是我的完整形式。
<%= form_for(@book) do |f| %>
<% if @book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :genre %><br />
<%= @items = Genre.find(:all)
select("genre", "description", @items.map {|u| [u.description,u.id]}, {:include_blank => true})%>
</div>
<div class="field">
<%= f.label :author %><br />
<%[email protected] = Author.find(:all)
select("author", "name", @items.map {|u| [u.name,u.id]}, {:include_blank => true}) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
那麼你想得到什麼? – fl00r