如何使用嵌套属性在多对一自引用模型中创建/更新Rails中的对象?
我的Rails 4应用程序有一个主题模型,允许多对多的自引用关系。 我基于这个奇妙的答案设置了模型,为多对多自连接创建模型,如果我手动填充关系表,它似乎有效。 让我们使用该模型来解决问题:
user.rb:
class User < ActiveRecord::Base # follower_follows "names" the Follow join table for accessing through the follower association has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow" # source: :follower matches with the belong_to :follower identification in the Follow model has_many :followers, through: :follower_follows, source: :follower # followee_follows "names" the Follow join table for accessing through the followee association has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow" # source: :followee matches with the belong_to :followee identification in the Follow model has_many :followees, through: :followee_follows, source: :followee end
follow.rb:
class Follow < ActiveRecord::Base belongs_to :follower, foreign_key: "follower_id", class_name: "User" belongs_to :followee, foreign_key: "followee_id", class_name: "User" end
一旦我手动填充Follow表,我就可以使用@ user.followers和@ user.followees等方法从模型中成功获取数据。
我遇到的问题是如何使用ActiveRecord以“Rails方式”正确创建Follow关系(Follower或Followee)。
在控制器中,代码将是什么样的创建新用户并使用嵌套属性同时为其分配现有的Followee (或多个Followees ?
我一直在尝试从视图传递变量的方法(多选输入),如:
user_params = {"user"=>"name","followees_attributes"=>{"id"=>{"1","2"}}}
然后在users_controller.rb中:
@user = User.new(user_params)
但是没有运气,而且我不确定我是否在这里(Rails的新手)。这感觉太简单了,但我对Rails感觉很多……呵呵。 如果我关闭但您需要查看错误消息,请告诉我。
编辑
我不确定这是否是“正确”的方式(不喜欢它),但我通过将嵌套的属性变量与模型分离,然后手动创建关系来实现它。
params = {"user"=>"name"},{"followees_attributes"=>{"id"=>{"1","2"}}}
然后在users_controller.rb中:
@user = User.new(user_params) @user.followees << User.find(1) @user.followees << User.find(2) @user.save
当然,你需要在那里进行一些重复检查以确保关系不存在,但从根本上说这可以完成工作。 还有更好的解决方案吗?