2009-06-21 50 views
4

我有一个虚拟属性的模型书籍,用于从书籍窗体创建编辑器。 代码看起来像: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 

回答

3

我相信它的原因是您的Book#editorial_string方法将始终返回“”。基于评论

def editorial_string 
    editorial ? editorial.name : "" 
    end 

更新:可以简化为以下

听起来像是你想要做的嵌套形式。 (请参阅accepts_nested_attributes_for in api docs)请注意,这是Rails 2.3中的新功能。

因此,如果您更新图书类

class Book < ActiveRecord::Base 
    accepts_nested_attributes_for :editorial 
    ... 
end 

(你也可以现在删除editorial_string =,太editorial_string方法)

和更新您的形式,类似下面的

... 
<% f.fields_for :editorial do |editorial_form| %> 
    <%= editorial_form.label :name, 'Editorial:' %> 
    <%= editorial_form.text_field :name %> 
<% end %> 
... 
1

的第一个问题是,

def editorial_string 
    self.editorial.name unless editorial.nil? 
    "" 
end 

总是返回 “” 因为那是最后一行。

def editorial_string 
    return self.editorial.name if editorial 
    "" 
end 

会解决这个问题。至于为什么验证不通过,我不知道,你在控制器中做什么?你得到了哪些验证错误?

+0

感谢您的修复。但我也有同样的问题:我在编辑表格中丢失了插入表单中的值。在控制器中,我有: 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

+0

你在开发服务器日志的外观和粘贴PARAMS。从那里我会尝试用脚本/控制台创建一本新书,并查看是否可以找到任何看起来不合适(或修复它)的东西。 – 2009-06-21 02:36:00