我有一个带有虚拟属性的模型书,用于从 Book 表单创建一个编辑器。代码如下所示:
class Book < ActiveRecord::Base
has_many :book_under_tags
has_many :tags, :through => :book_under_tags
has_one :editorial
has_many :written_by
has_many :authors, :through => :written_by
def editorial_string
self.editorial.name unless editorial.nil?
""
end
def editorial_string=(input)
self.editorial = Editorial.find_or_create_by_name(input)
end
end
和新的形式:
<% form_for(@book,
:html => { :multipart => true }) do |f| %>
<%= f.error_messages %>
...
<p>
<%= f.label :editorial_string , "Editorial: " %><br />
<%= f.text_field :editorial_string, :size => 30 %> <span class="eg">Ej. Sudamericana</span>
</p>
...
有了这个,当表单数据没有通过验证时,当表单重新显示时,我丢失了在编辑字段中提交的数据,并且还创建了一个新的编辑器。我该如何解决这两个问题?我对红宝石很陌生,我找不到解决方案。
更新我的控制器:
def create
@book = Book.new(params[:book])
respond_to do |format|
if @book.save
flash[:notice] = 'Book was successfully created.'
format.html { redirect_to(@book) }
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
end