Rails 4:如果存在记录,则更新而不是new

时间:2014-09-10 16:30:19

标签: ruby-on-rails

这是我的架构......

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

这可以阻止DB上的多个转录。但是,理想情况下我想要一个link_to语句,如果该用户/文档没有转录,那么他们可以创建一个新的,或者如果确实存在,当用户点击“Transcribe”时他们会编辑现有的转录。

1 个答案:

答案 0 :(得分: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
相关问题