简体   繁体   English

Rails 4:如果有记录,则更新而不是新的

[英]Rails 4: Update instead of new if a record exsists

Here is my schema... 这是我的图式...

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

Users can create transcriptions of document. 用户可以创建文档的副本。 I only want users creating one transcription of each document. 我只希望用户为每个文档创建一个副本。 In my document index view I have... 在我的文档索引视图中,我有...

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

However, with this link the user can create multiple transcriptions of a single document. 但是,使用此链接,用户可以创建单个文档的多个副本。 I have added a model validation that looks like... 我添加了一个看起来像...的模型验证

  validates_uniqueness_of :document_id, :scope => :user_id

This works to stop multiple transcriptions at the DB. 这样可以在DB处停止多个转录。 But, ideally I would like a link_to statement such that if no transcription exists for that user/document, then they could create a new one, or if one does exist, when the user clicks "Transcribe" they edit the existing transcription. 但是,理想情况下,我希望使用link_to语句,以便如果该用户/文档不存在任何转录,则他们可以创建一个新的转录,或者如果确实存在,则当用户单击“转录”时,他们可以编辑现有转录。

You can do a check in the new action 您可以在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM