2015-11-01 27 views
1

我有一个属性:连接表中的row_order(它也有它自己的模型:TodolistsTodo),我试图从另一个控制器(Todos)更新它。我怎样才能得到这个属性?无法更新Rails连接表中的额外属性

模型

class Todolist < ActiveRecord::Base 
    has_many :todos, through: :todolists_todos 
    has_many :todolists_todos 
end 

class Todo < ActiveRecord::Base 
    include RankedModel 
    ranks :row_order 
    has_many :todolists, through: :todolists_todos 
    has_many :todolists_todos 
end 

class TodolistsTodo < ActiveRecord::Base 
    belongs_to :todolists 
    belongs_to :todo 
end 

TodosController

def update_row_order 
    @todo = @parent.todos.find(todo_params[:todo_id]) 
    @todo.todolists_todo.where(:todolist_id => @parent.id).update_attribute :row_order,  todo_params[:todolists_attributes][:row_order] 
    @todo.save 

    render nothing: true 
    end 

private 

    def todo_params 
     params.require(:todo).permit(:todo_id, :todotype, :description, :status, :help, todolists_attributes: [:id, :row_order, :todolist_id, :todo_id]) 
    end 

的update_attribute线可以理解的失败,这是因为在那里产生一个CollectionProxy和update_attribute方法只能处理一个结果。不过,我也不想update_all。

调用Ajax控制器

todo_url = '/todolists/' + todolist_id + '/todos/update_row_order' 
    $.ajax(
     type: 'POST' 
     url: todo_url 
     dataType: 'json' 
     data: { todo: {todo_id: item_id, todolists_attributes: { row_order: position } } } 
    ) 
+0

你想更新什么? :row_order似乎是“Todo”的属性,而不是“TodolistsTodo”的属性。为什么一切都如此复杂?你没有要更新的待办事项的身份证吗? –

+0

在我PostgreSQL数据库的todolists_todos表中,它有一个row_order列,旁边是todolist_id和todo_id列。我有要更新的todo的id,但它没有row_order,因为todo是每个todolist的一部分,row_order将会不同。 –

回答

1

知道你TodolistsTodo:row_oder,知道,只能有一个每个TodoList的和计划TodolistTodo,假设@parent是todolist的,使用

@parent = Todolist.find params[:todolist_id] 
@item = @parent.todolists_todo.where(todo_id: params[:todo][:todo_id]).first 
@item.update_attribute :row_order, todo_params[:todolists_attributes][:row_order] 
+0

我明白了,所以我们通过采用第一个关系来确保update_attribute仅对一个结果起作用,因为只能有一个关系。我所要做的只是为模型添加一个主键(在添加row_order之前,连接表最初是一个没有模型的has_and_belongs_to_many)。 –