Rails - 有很多:通过,多个模型混乱
我正在处理 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 嵌套表单中。但在控制器中我似乎无法弄清楚如何正确添加标签。这是我的 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
它正在工作,但创建了多行。我希望能够创建标签,然后将位置、帐户、标签分配给标签。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样
How about