2011-10-20 29 views
0

使用Ruby on Rails來允許用戶添加項目帖子,就像Stackoverflow一樣。我可以使用普通的MySQL數據庫來做到這一點,但我不確定它如何與Mongoid一起工作。讓用戶添加「標籤」,同時在Rails上添加Mongoid和Ruby的文章

這是這個過程是如何工作的:

  1. 用戶寫入有關項目(客戶端,日期,描述)
  2. 添加標籤,如#1,在那裏他們只是單純的需要將每一個之間添加空格的一些細節一。
  3. 提交後

現在在我的模型,我試圖打破標籤成一個陣列(分裂那裏有一個空格),然後保存標籤一前一後。但是,項目和標籤的行不相互引用。項目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 

任何想法如何添加這些參考編號嗎?謝謝!

+0

哦,輸入_form.html.erb有這個

<%= f.label :tag_names %>
<%= f.text_field :tag_names %>

+0

StackOverflow的實際使用JavaScript來分割標籤,不知道他們做預處理,但它會在前端是微不足道的。 –

+0

那麼問題不在於分解標籤。我可以明白。它的tag_ids被引用我是標記中引用的項目和project_ids。 –

回答

1

我認爲你需要做的是:

t = Tag.find_or_create_by(:name => name) 
self.tags << t unless (self.tags.include? t) 
+0

我結束了爲標籤指定project_id = self.id然後:project_ids => [project_id]。然後標籤被賦予了project_ids,項目自動添加了tag_ids。感謝大家。 –

+0

我有完全相同的問題,它讓我瘋狂!您是否找到了更好的解決方案,然後直接分配ID? –

+0

你能解釋爲什麼我的答案不起作用嗎? <<任務應該爲您處理外國身份證件。 –