I am using many-to-many using :through since I need to store additional
information in the join table.
I am doing this and it seems to work. I want to verify that this is the
best
way to do this.
Tables
foods - id, food
foodallergies - food_id, symptom_id, a few other columns
symptoms - id, symptom
Models
class Food < ActiveRecord::Base
has_many :foodallergies
has_many :symptoms, :through => :foodallergies
end
class Symptom < ActiveRecord::Base
has_many :foodallergies
has_many :foods, :through => :foodallergies
end
class Foodallergy < ActiveRecord::Base
belongs_to :foods
belongs_to :symptoms
end
I have a JournalEntry model that stores foods and symptoms as
comma-seperated strings. Upon record creation in the JournalEntry, I
want to
parse the foods and symptoms and create a many to many relationship
between
them. I do this like this in the create method in the JournalController
def create
params[:journal_entry][“user_id”] = @session[:user].id
@journal_entry = JournalEntry.new(params[:journal_entry])
if @journal_entry.save
# parse the foods and create a new record if food not already in
db
params[:journal_entry][“eat”].split(%r{,\s*}).each do |food|
f = Food.find(:first, :conditions => [“food=?”, food.strip])
unless f
f = Food.create(:food => food)
end
params[:journal_entry]["symptoms"].split(%r{,\s*}).each do
|symptom|
s = Symptom.find(:first, :conditions => [“symptom=?”,
symptom.strip])
unless s
s = Symptom.create(:symptom => symptom)
end
# create join
f.foodallergies.create(:food_id => f.id, :symptom_id => s.id)
end
end
flash[:notice] = 'JournalEntry was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end
Is this the best way to do it? Since I am using create, there is a
database
interaction on every ‘create’. Is there a way to leverage ActiveRecord
functionality to batch the database interaction?
Thanks in advance,
Vaishal