Rails 4: Update instead of new if a record exsists -


here schema...

create_table "documents", force: true |t|     t.string   "document_name" ...   end    create_table "transcriptions", force: true |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 |t|     t.string   "email"     t.string   "password_digest"     t.string   "role" ...   end 

users can create transcriptions of document. want users creating 1 transcription of each document. in document index view have...

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

however, link user can create multiple transcriptions of single document. have added model validation looks like...

  validates_uniqueness_of :document_id, :scope => :user_id 

this works stop multiple transcriptions @ db. but, ideally link_to statement such if no transcription exists user/document, create new one, or if 1 exist, when user clicks "transcribe" edit existing transcription.

you can check in new action

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 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -