2017-06-22 98 views
0

说我有两个表,trees和​​和一个连接表tree_apples。假设tree_apples表有几个重要列,分别叫做rotten(boolean)和branch(int)。Rails update_nested_attributes。如果存在,HOw会进行更新,如果不存在则创建?

说,在控制器trees,我有这样的:

@tree.update_nested_attributes(tree_params)和我tree_params方法是这样的:

tree_apple_params: { 
    :apple_id, 
    :rotten, 
    :branch 
} 

说,我已经更新有tree_apple与ID树3即rotten: truebranches: nil和传入参数到此控制器更新分支具有这样的参数:

tree_apple_params: [{ 
    apple_id: 3, 
    rotten: nil, 
    branch: 5 
    }, 
    { 
    apple_id: 4, 
    rotten: nil, 
    branch: 6 
    }, 
    ... 
] 

所以这是params来创建或更新一堆tree_apples。参数来自的页面想要更新tree_apple的分支,该分支引用3的apple_id,并且对于此tree_apple,它不提供任何关于腐烂状态的输入。我不想创建另一个tree_apple,它引用apple_id: 3对于rotten_state具有nil。我想更新现有的tree_apple。所以,对于这个tree_apple,我想找到它,然后更新它与分支5.但对于参考苹果,不存在此树上的所有其他参数,我想创建tree_apples如果tree_apple不存在。

有没有办法做到这一点?这个逻辑是否属于控制器或模型中的某种回调?

回答

0

查找到沿线的find_or_create_by

东西:

tree_params.each do |params| 
    tree_apple = TreeApple.find_or_create_by(apple_id: params[:apple_id]) 
    tree_apple.update_attributes(branch: params[:branch], rotten: params[:rotten]) 
end 

在你的控制器。

+0

@jwan没有能够解决问题了吗? – George

0

如果您要更新记录,您必须传递tree_apple记录的ID。

tree_apple_params: [{ 
id: 1, #passing the id of the tree_apple record here will update existing records 
apple_id: 3, 
rotten: nil, 
branch: 5 
}, 
{ #passing NO id here will create records 
apple_id: 4, 
rotten: nil, 
branch: 6 
}, 
... 
] 

很显然允许ID在你的PARAMS:

tree_apple_params: { 
    :id, 
    :apple_id, 
    :rotten, 
    :branch 
} 
+0

你可以通过id以外的任何其他属性来更新'tree_apples'吗?你可以告诉rails更新,只要'apple_id'是相同的呢? – Jwan622

+0

如果你没有通过ID,你必须找到记录来更新它@George在他的回答中 –