花在谷歌一整天,却找不到答案。 :\
Spent all day on Google, but can't find an answer. :\
我有用户和Core_Values之间的HABTM关系。
I have a HABTM relationship between Users and Core_Values.
class CoreValue < ActiveRecord::Base
has_and_belongs_to_many :users
class User < ActiveRecord::Base
has_and_belongs_to_many :core_values
在我的控制,我需要做的两回事:
In my controller, I need to do two separate things:
如果一个CoreValue不存在,创建一个新的,它与给定用户ID相关联, 假设我知道一个特定的CoreValue确实存在,创建该协会没有建立任何新CoreValues或用户有关#1,我得到这个工作:
For # 1, I've got this to work:
User.find(current_user.id).core_values.create({:value => v, :created_by => current_user.id})
这将创建一个新的CoreValue有:价值:CREATED_BY并创建关联
This creates a new CoreValue with :value and :created_by and creates the association.
有关#2,我已经尝试了一些事情,但不能完全似乎只建立关联。
For # 2, I've tried a few things, but can't quite seem to create the association ONLY.
感谢您的帮助!
您可以在两个步骤中做到这一点,使用非常有用 find_or_create
方法。 find_or_create
将首先尝试找到一个记录,如果它不存在,创建它。像这样的东西应该做的伎俩:
You can do this in a two-step procedure, using the very useful find_or_create
method. find_or_create
will first attempt to find a record, and if it doesn't exist, create it. Something like this should do the trick:
core_value = CoreValue.find_or_create_by_value(v, :created_by => current_user.id)
current_user.core_values << core_value
一些注意事项:
Some notes:
在第一行会发现或创造的价值 v
。如果它不存在,创建完成后,将设置 CREATED_BY
到 current_user.id
。
有没有必要做 User.find(current_user.id)
,因为这将返回相同的对象为 CURRENT_USER
。
current_user.core_values
是一个数组,可以在另一台价值通过轻松地添加到它&LT;&LT;
。
The first line will find or create the value v
. If it doesn't exist and is created, it will set the created_by
to current_user.id
.
There's no need to do User.find(current_user.id)
, as that would return the same object as current_user
.
current_user.core_values
is an array, and you can easily add another value to it by using <<
.
有关简洁起见,下面将与上述相同的$ C $℃实施例:
For brevity, the following would be the same as the code example above:
current_user.core_values << CoreValue.find_or_create_by_value(v, :created_by => current_user.id)