我是一个 Rails 菜鸟,我在解决问题时遇到了一些麻烦。
我将 Rails 3.2.13 与以下 gem 一起使用(除了默认 gem 之外):
gem 'devise'
gem 'cancan'
gem 'cocoon'
gem 'best_in_place'
我正在使用 cocoon 来处理嵌套模型,在这种情况下,我有一个(设计)用户,他有 has_many
个项目,每个项目有 has_many
个任务。
我能够通过以下方式获取所有要显示的信息(并在点击时变得可编辑):
<% @project.tasks.each do |task| %>
<%= best_in_place task, :description, :path => tasks_path, :type => :input %>
<% end %>
我的问题是我无法获得 best_in_place 来保存对我的嵌套任务属性的更新。
项目模型:
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
attr_accessible :description, :name, :tasks_attributes, :user_id, :tasks
accepts_nested_attributes_for :tasks, :reject_if => :all_blank, :allow_destroy => true
end
任务模型:
class Task < ActiveRecord::Base
belongs_to :project
attr_accessible :description, :done, :hours
end
项目负责人:
class ProjectsController < ApplicationController
before_filter :authenticate_user!
def show
@project = Project.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @project }
end
end
def update
@project = Project.find(params[:id])
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to @project, :notice => 'Project was successfully updated.' }
#format.json { head :no_content }
format.json { respond_with_bip(@project) }
else
format.html { render :action => "edit" }
#format.json { render :json => @project.errors, :status => :unprocessable_entity }
format.json { respond_with_bip(@project) }
end
end
end
end
项目 -> show.html.erb:
<% @project.tasks.each do |task| %>
<li class="module-list-item ui-state-default clear">
<section class="task-name left">
<%= best_in_place task, :description, :path => tasks_path, :type => :input %>
</section>
</li>
<% end %>
最佳答案
虽然官方不支持这种用法(正如@Ich 指出的那样),但有一个解决方法。无需任何额外的 Controller 。您只需要将 param
参数传递给 best_in_place。
class Unicycle < AR::Base
has_one :wheel
accepts_nested_attributes_for :wheel, update_only: true
end
best_in_place unicycle.wheel, :last_rotation,
path: unicycle_path(unicycle.id), type: :input,
param: "unicycle[wheel_attributes]"
请注意,对于汽车
,有_many :wheels
(或独轮车
,有_one :wheel>,情况稍微复杂一些
其中 update_only
对你不起作用)。
car.wheels.each do |wheel|
best_in_place wheel, :last_rotation,
path: car_path(car.id), type: :input,
param: "car[wheel_attributes][id]=#{wheel.id}&car[wheel_attributes]"
# Note that you have to pass the ID of the wheel in this case
end
适用于 v3.0.3,可能也适用于更早的版本,但我尚未测试。
关于ruby-on-rails - Rails 3 问题与 best_in_place 和嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890101/