使用Ruby on Rails來允許用戶添加項目帖子,就像Stackoverflow一樣。我可以使用普通的MySQL數據庫來做到這一點,但我不確定它如何與Mongoid一起工作。讓用戶添加「標籤」,同時在Rails上添加Mongoid和Ruby的文章
這是這個過程是如何工作的:
- 用戶寫入有關項目(客戶端,日期,描述)
- 添加標籤,如#1,在那裏他們只是單純的需要將每一個之間添加空格的一些細節一。
- 提交後
現在在我的模型,我試圖打破標籤成一個陣列(分裂那裏有一個空格),然後保存標籤一前一後。但是,項目和標籤的行不相互引用。項目tag_ids = []和標籤project_ids = []
project.rb模型
class Project
include Mongoid::Document
include Mongoid::MultiParameterAttributes
field :client, :type => String
field :description, :type => String
field :url, :type => String
field :project_date, :type => Date
has_and_belongs_to_many :tags
attr_accessor :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(" ")
end
def assign_tags
@project = self
@project_id = self.id
if @tag_names
self.tag_names = @tag_names.split(/\s+/).map do |name|
Tag.find_or_create_by(:name => name)
end
end
end
end
tag.rb模型
class Tag
include Mongoid::Document
field :name, :type=> String
has_and_belongs_to_many :projects
end
任何想法如何添加這些參考編號嗎?謝謝!
哦,輸入_form.html.erb有這個
<%= f.text_field :tag_names %>
StackOverflow的實際使用JavaScript來分割標籤,不知道他們做預處理,但它會在前端是微不足道的。 –
那麼問題不在於分解標籤。我可以明白。它的tag_ids被引用我是標記中引用的項目和project_ids。 –