2014-09-10 64 views
1

這裏是我的架構......軌道4:更新,而不是新的,如果一個記錄exsists

create_table "documents", force: true do |t| 
    t.string "document_name" 
... 
    end 

    create_table "transcriptions", force: true do |t| 
    t.text  "content" 
    t.integer "user_id" 
    t.integer "document_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "users", force: true do |t| 
    t.string "email" 
    t.string "password_digest" 
    t.string "role" 
... 
    end 

用戶可以創建的文件轉錄。我只希望用戶創建每個文檔的一個轉錄。在我的文檔索引視圖中,我有...

<td><%= link_to 'Transcribe', new_document_transcription_path(document, current_user) %></td> 

但是,通過此鏈接,用戶可以創建單個文檔的多個副本。我已添加模型驗證,看起來像...

validates_uniqueness_of :document_id, :scope => :user_id 

這可以停止在數據庫的多個副本。但是,理想情況下,我想要一個link_to語句,以便如果該用戶/文檔不存在任何轉錄,則可以創建一個新的轉錄,或者如果存在,則當用戶單擊「轉錄」時編輯現有轉錄。

回答

0

你可以做一個檢查在new行動

def new 
    @transcription = current_user.transcriptions.where(:document => params[:document_id]).first 
    if @transcription 
    render action: 'edit' 
    else 
    @transcription = Transcription.new 
    render action: 'new' 
    end 
end 
+2

或者使用'first_or_initialize' :) – Santhosh 2014-09-10 16:53:02

相關問題