簡體   English   中英

帶有best_in_place和嵌套屬性的Rails 3問題

[英]Rails 3 issue with best_in_place and Nested Attributes

我有點Rails新手,但遇到問題時遇到了一些麻煩。

我正在將Rails 3.2.13與以下寶石(除了默認寶石)一起使用:

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來保存對嵌套Task屬性的更新

項目模式

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所指出的),但是有一種解決方法。 無需任何其他控制器。 您只需要將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]"

請注意,對於具有has_many :wheelsCar (或對於具有has_one :wheel update_only ,其中update_only無法為您使用的Unicycle來說,它稍微復雜一些。

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,可能也適用於更早的版本,但我尚未測試。

根據https://github.com/bernat/best_in_place/issues/51,best_in_place不支持此功能。

寶石的作者認為,就地編輯只能修改一個模型的屬性,因此更改另一模型的屬性不在范圍之內。

我的看法:我個人對此表示遺憾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM