2014-09-10 53 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