Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

activerecord - Rails: Has and belongs to many (HABTM) -- create association without creating other records

Spent all day on Google, but can't find an answer. :

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:

  1. If a CoreValue does not exist, create a new one and associate it with a given user id, and
  2. Assuming I know a particular CoreValue does exist already, create the association without creating any new CoreValues or Users

For # 1, I've got this to work:

User.find(current_user.id).core_values.create({:value => v, :created_by => current_user.id})

This creates a new CoreValue with :value and :created_by and creates the association.

For # 2, I've tried a few things, but can't quite seem to create the association ONLY.

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • 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 <<.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...