2011-01-12 44 views
0

我有4個模型,我正在處理。我有一個帳戶,位置,標記和標記模型。我有一個像如下導軌 - 有很多:通過,與多個模型混淆

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 

我遇到的問題是,當我創建的形式,它是在位置頁面設置。我希望能夠標記一個位置,但讓它與一個帳戶關聯,並且正在努力處理正確的形式和控制器邏輯的邏輯。

在表單中,/ location/1/tags嵌套窗體。但在控制器中,我似乎無法弄清楚如何正確添加標籤。這是我的標籤控制器

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

這是工作有點,但創建多行。我希望能夠創建標籤,然後將位置,帳戶,標籤分配給標籤。

+0

你怎麼有belongs_to的:在您的標籤模型住所。這不應該是belongs_to:帳戶嗎? – JosephL 2011-01-12 21:06:11

+0

約瑟夫你是正確的......這是一個爛攤子和糊糊..回合布特 – bokor 2011-01-13 01:32:45

回答

1

如何

@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)