我有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 /标签嵌套表格。但在控制器中我似乎无法弄清楚如何正确添加标签。这是我的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
它有点工作,但创建了多行。我希望能够创建标签,然后将位置,帐户,标签分配给标签。
答案 0 :(得分: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)