2013-07-26 53 views
2

我是一個Rails noob的一點,我有一些麻煩讓我的頭問題。Rails 3問題與best_in_place和嵌套的屬性

我使用Rails 3.2.13具有以下寶石(除了默認的寶石):

gem 'devise' 
gem 'cancan' 
gem 'cocoon' 
gem 'best_in_place' 

我使用繭嵌套模式工作,在這種情況下,我有(設計)用戶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 %> 
+0

當你更新時,你的params []中有什麼?也許best_in_place發送錯誤的參數,params [:project]和update_attributes(params [:project])可能失敗 – stef

回答

0

根據https://github.com/bernat/best_in_place/issues/51這不是由best_in_place支持。

寶石的作者認爲,就地編輯應該只修改一個模型的屬性,所以更改另一個模型的屬性不在範圍內。

我的意見:我個人感到遺憾的是這個決定。

1

儘管這種使用方式沒有得到正式支持(正如@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]" 

請注意,這是稍微複雜一點的Car,這has_many :wheels(或爲Unicyclehas_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,可能還有更早的版本,但我沒有測試過。