0

I have 4 models i'm dealing with. I have an Account, Location, Tag, and Tagging Model. I have set it up like follows

class Tag < ActiveRecord::Base

  # belongs_to :shelter
  has_many :taggings, :dependent => :destroy
  has_many :locations, :through => :taggings
  has_many :accounts, :through => :taggings

end

class Tagging < ActiveRecord::Base

  belongs_to :location
  belongs_to :tag
  belongs_to :shelter

end

class Account < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings, :dependent => :destroy
end

class Location < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings, :dependent => :destroy
end

create_table :taggings, :force => true do |t|
  t.references :account
  t.references :location
  t.references :tag
  t.timestamps
end

The problem I'm having is when I create the form it is on the Location Page. I want to be able to tag a location but have it associated with an account and am struggling with the logic of how to do the form and controller logic correctly

In the Form I have, /location/1/tags nested form. But in the controller I can't seem to figure out how to add the tag correctly. Here is my TagsController

def create
    @tag = Tag.find_or_create_by_name(params[:tag][:name])
    @location = @current_account.locations.find(params[:location_id])
    @location.tags << @tag
end

It is working kinda, but creating multiple rows. I want to be able to create the Tag then assign the Location, Account, Tag to the Tagging.

bokor
  • 1,829
  • 1
  • 19
  • 25

1 Answers1

1

How about

@tag = Tag.find_or_create_by_name(params[:tag][:name])
@location = @current_account.locations.find(params[:location_id])
@tagging = Tagging.create(:tag => @tag, :location => @location, :shelter => @current_account)
David Sulc
  • 25,946
  • 3
  • 52
  • 54
  • Worked like a charm. Thank you for this tip as I didn't know you could do the Tagging.create that way. Looks like you gave me more work now as I'm going to have to clean up some other code. – bokor Jan 13 '11 at 01:33
  • Do you recommend a good way to do this from the form. I have another similar object that I have with a similar set up. Called placements so if I were to do Placements.new in the form but had these variables to set like above, would you set them in the form as hidden fields(so it minimizes queries) or a lookup in the controller – bokor Jan 13 '11 at 01:36
  • Not sure I understand what you mean, but it seems you'd be executing the same number of queries: either before the form is rendered (to set the hidden field values), or after the form is posted (to retrieve the model instances). Given that "premature optimization is the root of all evil", I wouldn't worry about saving a few queries until it really is a problem (unless of course you're performing needless queries in loops or something). – David Sulc Jan 13 '11 at 01:51