0

我在使用.user_ids

我的通信模型如下所示:

class communication
 has_many :recipients
 has_many :users, :through => :recipients
end

在我为通信控制器创建操作中,我试图手动添加user_ids到通信对象,如下所示:

@communication = new Communications(params[:communication])
@communication.user_ids << id
logger.debug @communication.user_ids # is empty

我无法弄清楚为什么@communication.user_ids数组是空的,即使我像这样进行硬编码 id :

@communication = new Communications(params[:communication])
@communication.user_ids << 1
logger.debug @communication.user_ids # is still empty!

我仍然得到一个空@communication.user_ids数组。

我的方法是否遗漏了什么?有什么技巧可以让它工作吗?

提前致谢!

4

1 回答 1

1

既然是has_many :through,也许你需要提供完整的对象,以便可以顺利地创建关系。尝试这个:

@communication = Communication.new params[:communication]
@communication.users << User.find( 1 )
@communication.user_ids  # should be [ 1 ]
于 2009-09-21T04:49:20.583 回答