Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用嵌套属性在多对一自引用模型中创建/更新Rails中的对象?_Ruby On Rails_Ruby_Ruby On Rails 4_Activerecord - Fatal编程技术网

Ruby on rails 如何使用嵌套属性在多对一自引用模型中创建/更新Rails中的对象?

Ruby on rails 如何使用嵌套属性在多对一自引用模型中创建/更新Rails中的对象?,ruby-on-rails,ruby,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby,Ruby On Rails 4,Activerecord,我的Rails 4应用程序有一个主题模型,允许多对多的自我引用关系。我在为多对多自联接创建模型的基础上建立了模型,如果手动填充relationships表,它似乎可以工作。让我们将该模型用于问题的目的: user.rb: class User < ActiveRecord::Base # follower_follows "names" the Follow join table for accessing through the follower association has_

我的Rails 4应用程序有一个主题模型,允许多对多的自我引用关系。我在为多对多自联接创建模型的基础上建立了模型,如果手动填充relationships表,它似乎可以工作。让我们将该模型用于问题的目的:

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
然后在users_controller.rb中:

@user = User.new(user_params)
@user = User.new(user_params)
@user.followees << User.find(1)
@user.followees << User.find(2)
@user.save
但是运气不好,我也不确定我是否在这里(对Rails来说是新手)。感觉太简单了,但我对Rails有很多这种感觉……呵呵。如果我很接近,但您需要查看错误消息,请让我知道

编辑

我不确定这是否是一种“正确”的方法(感觉不太像),但我通过将嵌套的属性变量从模型中分离出来,然后手动创建关系,实现了这一点

params = {"user"=>"name"},{"followees_attributes"=>{"id"=>{"1","2"}}}
然后在users_controller.rb中:

@user = User.new(user_params)
@user = User.new(user_params)
@user.followees << User.find(1)
@user.followees << User.find(2)
@user.save
@user=user.new(用户参数)

@user.followes您应该为
follows
的两列添加唯一索引,以防止重复。是的,可以。谢谢您应该在
后面的两列中添加一个唯一的索引,以防止重复。是的,可以。谢谢