2011-01-12 90 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)