我有一个text_field,用户可以在标签中输入(就像stackoverflow上的标签)。它们可以用逗号分隔标签。现在,我知道如何拆分标签了。但作为n00b,我被困在了下一阶段。我有一个标签表,一个Trip表和一个tags_trips (一个trip可以有多个关键字,但我希望这些关键字在我的数据库中是唯一的,这样当它们存在时,它们可以在其他trip中再次使用)。
真正的问题是:在拆分字符串之后,如何检查关键字是否存在并获取要放入tags_trips表中的现有ID,如果不存在,如何一次性获得刚刚在tags_trips表中拆分的数组?
以下是我的表的概述:
Trip
:id => :integer,
:title => :string,
:description => :text,
:user_id => :integer,
:created_at => :datetime,
:updated_at => :datetime
Tag
:id => :integer,
:title => :string,
:created_at => :datetime,
:updated_at => :datetime
tags_trip
:tag_id => :integer,
:trip_id => :string我在我的模型中使用了标签和Trip之间的has_and_belongs_to_many关联,并在Trip表单中通过fields_for :tags获取text_field。(注意:表单工作正常,我已经设法将键入的关键字字符串输入到我的标签表中!)只是没有分开;-))
提前感谢!
发布于 2012-11-06 20:12:40
我已经弄明白了。我不确定这是不是最好的方法,但它是有效的!这就是我所做的:我循环遍历params:trip (如果存在)。并再次循环遍历,同时使用逗号将其拆分。而不是在循环中,我在trip.tags上做了一个find_or_create_by,瞧!他们得救了。之后,我从params:trip中删除了tags_attributes,这样它就不会保存在update_Attributes上。ChuckE,你帮了我大忙,万分感谢!
代码:
def update
@trip = Trip.find(params[:id])
if params[:trip][:tags_attributes].present?
params[:trip][:tags_attributes].each do |tag|
@a = tag[1]['title']
@a.split(',').each do |single|
@trip.tags.create(:title => single)
end
end
end
#Delete the tags attributes from the trip array so it will not be saved.
params[:trip].delete('tags_attributes')
respond_to do |format|
if @trip.update_attributes(params[:trip])
format.html { redirect_to @trip, notice: 'Trip was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @trip.errors, status: :unprocessable_entity }
end
end
end发布于 2012-11-01 17:50:19
如果您希望标记的标题在整个应用程序中都是唯一的,则需要在表上设置唯一性索引。除此之外,has_and_belongs_to_many还有一个:uniq字段,当设置为true时,将忽略重复。如果这仍然不起作用,可以尝试在创建标签时使用find_or_create_by_title助手。
https://stackoverflow.com/questions/13174104
复制相似问题