我的Rails應用程序中有一個嵌套窗體/模型,除了before_save方法無法訪問父級用戶與嵌套形式,工作時的對象。它在我的ForumControler控制器保存子模型本身雖然..Ruby rails 3嵌套窗體無法保存,因爲before_save方法訪問的對象爲零的父模型
所以這裏時簡化代碼
class Forum < ActiveRecord::Base
has_many :forum_post, :dependent => :destroy
belongs_to :project
accepts_nested_attributes_for :forum_post, :reject_if => :all_blank
end
class ForumPost < ActiveRecord::Base
belongs_to :forum
belongs_to :user
before_save :toggle_forum
has_attached_file :attachment
def toggle_forum
#a bunch of code
#one line tries to access @user.id but it fails because @user is nil
@user.id
end
end
然後工作正常,雖然這將更新這個我
def update
@forum = Forum.find(params[:id])
if @forum.update_attributes(params[:forum])
redirect_to(user_forum_path(@user,@forum.project,@forum), :notice => 'Forum was successfully updated.')
else
render :action => 'submit'
end
末
在我看來:
<%= form_for(@forum, :url => user_forum_path, :html => { :multipart => true, :id => :project }) do |f| %>
<div class="form-label-row summary-text">
<%= f.label(:summary_text, 'Final Summary') %>
<%= f.text_area :summary_text %>
</div>
<%= f.fields_for :forum_post,$forum_post do |child_form| %>
<div class="form-row-left attachment">
<%= child_form.label :attachment %>
<%= child_form.file_field :attachment %>
</div>
<!-- I tried adding with and without the next 2 hidden fields and it failed either way -->
<%= child_form.hidden_field :user_id, :value=>@user.id %>
<%= child_form.hidden_field :forum_id, :value=>@forum.id %>
<% end %>
<%= hidden_field(:forum, :state, :value => :student_completed) %>
<div class="form-buttons" id="submit">
<%= f.submit "Submit Project" %>
</div>
<% end %>
的問題是,如果@user爲零保存forum_post爲嵌套對象時..如果我救forum_post在自己的模式它的工作原理精細。任何想法爲什麼從父對象保存時@user變量沒有被填充?
@user在哪裏創建的?它似乎來自你的更新行動的任何地方。 – bostonou 2012-01-17 04:41:33