我将嵌套对象保存在它们所属的对象中,但是当我这样做时,它们不会使用控制器即时保存而是父控制器。
class Project < ActiveRecord::Base
belongs_to :company
belongs_to :user
has_many :tasks
accepts_nested_attributes_for :tasks, :allow_destroy => true
end
在视图中我有类似的东西
<% form_for @project do |c| %>
<% c.fields_for :tasks, @project.tasks.last do |p| %>
<%= p.text_field :name %>
<% end %>
<%= submit_tag '+' %>
<% end %>
所以我正在尝试做的是使用字段更新用户字段,在控制器中指定最后一个字段。
def show
@project = Project.find(params[:id])
@project.tasks.build
@project.tasks.last.user = current_user # this should pass to the show.html.erb, to be saved back
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @project }
end
end
我想也许解决方法是检查是否在嵌套对象中设置了用户名,如果没有用当前用户填充它:
def update
@project = Project.find(params[:id])
@project.user = current_user
#find anything @project.....user blank and set to current user
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to(@project, :notice => 'Project was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @project.errors, :status => :unprocessable_entity }
end
end
end
我希望这是解决方案,它是如何做到的?
目前正在运行的示例是http://severe-fire-37.heroku.com