【问题标题】:Update creating a new record if values are not modified如果未修改值,则更新创建新记录
【发布时间】:2015-02-16 12:35:53
【问题描述】:

如果我编辑和更改值,代码工作正常,但如果我更新相同的值,它会创建一条新记录。

我只是在关注 ruby​​ 教程并被困在这个问题上。我对 ruby​​ 和 rails 还很陌生。

控制器:articles_controller.rb

class ArticlesController < ApplicationController

def create
    #render plain: params[:article].inspect
    @article = Article.new(article_params)

    if @article.save
        redirect_to @article
    else
        render 'new'
    end
end

def new
    @article = Article.new
end

def show
    @article = Article.find(params[:id])
end

def index
    @articles = Article.all    
end

def edit
    @article = Article.find(params[:id])
end

def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
        redirect_to @article
    else
        render 'edit'
    end
end


private
  def article_params
    params.require(:article).permit(:title_article, :text_article, :author_article)
  end

end

表格:_form.html.erb

<% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:
      </h2>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
<% end %>

<p>
    <%= f.label :title_article ,"Title" %><br>
    <%= f.text_field :title_article %>
</p>

<p>
    <%= f.label :text_article ,"Content" %><br>
    <%= f.text_area :text_article %>
</p>

<p>
    <%= f.label :author_article ,"Author" %><br>
    <%= f.text_field :author_article %>
</p>

<p>
    <%= f.submit "Submit" %>
</p>
<% end %>

新文章页面:new.html.erb

<h1>Edit Page</h1>

<%= render 'form' %>

<%= link_to 'Back', articles_path %>

编辑文章页面:edit.html.erb

<h1>New Page</h1>

<%= render 'form' %>

<%= link_to 'Back', articles_path %>

【问题讨论】:

  • 在更新界面,当你在字段中再次输入相同的内容时,上面的代码插入新记录不更新?
  • 请同时出示您的表格。
  • @Ansar 是的。在编辑页面上,如果我没有进行任何更改并按提交,它会创建一条新记录,而当我更改某些内容时,它会修改相同的记录。
  • 你能检查你的控制台是否有发送到服务器的参数?特别是,id 是否发送了预期值?您还确定它真的提交了一条新记录,而不仅仅是 HTML 副本?
  • Emm...你的&lt;%= form_for(@article) do |f| %&gt;呢??

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

正如@Cyril DD 在评论中所说,您在_form.html.erb 中的代码应该在第一行包含&lt;%= form_for(@article) do |f| %&gt;。 (我想它应该会引发语法错误......)

_form.html.erb

<%= form_for(@article) do |f| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:
      </h2>
...

我复制了您的所有代码并添加了该行。然后,一切正常。即使在编辑中没有更改值,它也没有写新文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多