How to create/update objects in Rails in a many-to

2019-08-11 04:08发布

问题:

My Rails 4 app has a topic model that allows many-to-many self-referential relationships. I set up the model based on this fantastic answer on creating a model for many-to-many self joins, and it appears to work if I populate the relationships table manually. Let's use that model for the purposes of the question:

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

Once I manually populate the Follow table, I can successfully get data from the model using methods like @user.followers and @user.followees.

Where I'm stuck is in how to create the Follow relationships (Follower or Followee) using ActiveRecord properly, in the "Rails way."

In the controller, what would the code look like to create a new User and assign it an existing Followee (or multiple Followees at the same time using nested attributes?

I've been trying approaches that pass vars from the view (multi-select input) like:

user_params = {"user"=>"name","followees_attributes"=>{"id"=>{"1","2"}}}

And then in users_controller.rb:

@user = User.new(user_params)

but with no luck, and I'm not sure if I'm even in the right ballpark here (new to Rails.) It feels too simple, but I get that feeling a lot with Rails...hehe. If I'm close but you need to see error messages, please let me know.

EDIT

I'm not sure if this is the "right" way to do this (doesn't feel like it), but I got it working by separating the nested attributed vars from the model, and then manually creating the relationship.

params = {"user"=>"name"},{"followees_attributes"=>{"id"=>{"1","2"}}}

And then in users_controller.rb:

@user = User.new(user_params)
@user.followees << User.find(1)
@user.followees << User.find(2)
@user.save

Naturally you'll need some duplicate checking in there to make sure the relationship doesn't already exist, but fundamentally this gets the job done. Any better solutions out there?