2013-03-17 65 views
0

我正在構建我的第一個Rails應用程序,直到現在一切正常,但後來我發現以下場景:一個演示文稿應該有N個迭代。我沒有使用REST。所以,我試圖做一個簡單的表單來創建迭代。Rails 3:保存方法不會工作

這些機型:

class Presentation < ActiveRecord::Base 
    has_many :iterations 
end 

class Iteration < ActiveRecord::Base 
    belongs_to :presentation 
    attr_accessible :presentation_id, :description, :delivery_date, :file 
    validates :presentation_id, :presence => {:message => 'is required.'} 
end 

這些都是在控制器的動作:

#Shows Form 
def add 
    @iteration = Iteration.new 
    @presentation = Presentation.find(params[:id]) 
end 

#Saves Form 
def save 
    @iteration = Iteration.new(params[:iteration]) 
    @iteration.delivery_date = Time.now 
    if @iteration.save 
    flash[:notice] = "Saved succesfully!" 
    else 
    flash[:error] = "Changes were not saved." 
    end 
    redirect_to root_url 
end 

這將是HAML的觀點:

= form_for @iteration, :url => { :action => "save", :method => "post" }, :html => { :multipart => true } do |f| 

- if @iteration.errors.any? 
    There were some errors: 
    .notice-text.fg-color-white 
    %ul.notice 
    - for message in @iteration.errors.full_messages 
     %li= message 
%br 

.field 
    = f.label :description, "Description" 
    = f.text_area :description, :class=>"form-text-area", :rows=>5 
.field 
    = f.label :file, "Upload File" 
    = f.file_field :file 
.field 
    = hidden_field_tag :presentation_id, @presentation.id 
%br 
= f.submit "Save" 

問題是,保存方法不會保存,但@ iteration.errors.count的視圖上的值是0. 我用然後保存!相反,當我在另一篇文章中讀到時,以這種方式拋出以下錯誤:

驗證失敗:需要演示。

我搞不​​清楚我做錯了什麼。請注意,在我曾經有過「f.hidden_​​field」而不是「hidden_​​field_tag」的視圖中,但是出於其他一些原因我改變了它,但是在此之前我得到了同樣的錯誤。

+0

我注意到沒有任何屬性到達控制器... – 2013-03-17 20:34:00

回答

1

你HAML,

hidden_field_tag :presentation_id 

需求是,

f.hidden_field :presentation_id, :value => @presentation.id 
+0

我嘗試了f.hidden_​​field,但仍然收到相同的錯誤。 – 2013-03-17 20:23:11

+0

我已經更新了添加'value'屬性的答案。 – Sam 2013-03-17 20:26:30

+0

我試過你的解決方案,但同樣的錯誤...我發現如果我做了像@ iteration.presentation = Presentation.find之類的東西,那麼它實際上是有效的。我的意思是,這就像表單傳遞的對象從不附加到任何表示= / – 2013-03-17 20:29:55