2009-06-21 99 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