我有一个虚拟属性的模型书籍,用于从书籍窗体创建编辑器。 代码看起来像:Rails:虚拟属性和表单值
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>
...
这样,当表单数据没有经过我失去了在编辑领域submited的数据验证时,表单重新,并且还创建了一个新的编辑器。我如何解决这两个问题?我在ruby中很新,我找不到解决方案。
更新我的控制器:
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
感谢您的修复。但我也有同样的问题:我在编辑表格中丢失了插入表单中的值。在控制器中,我有: def create @book = Book.new(params [:book]) respond_to do | format |如果@ book.save flash:[:notice] ='Book was successfully created。' format.html {redirect_to的(@book)} 其他 format.html {渲染:行动=> “新”} 结束 月底结束 可以 – Castro 2009-06-21 02:23:10
你在开发服务器日志的外观和粘贴PARAMS。从那里我会尝试用脚本/控制台创建一本新书,并查看是否可以找到任何看起来不合适(或修复它)的东西。 – 2009-06-21 02:36:00