【问题标题】:Rails - Saving in a table and update/creating in another oneRails - 保存在一个表中并在另一个表中更新/创建
【发布时间】:2019-10-15 03:40:08
【问题描述】:

我正在创建一个小应用程序来管理我自己的在线投资组合,但我无法解决 update 的问题。

我的数据库的主表是works,然后是表authors 和clients,其中我将字段authorName 和clientName 设置为unique。作者和客户可以有多个作品,但一个作品只能有一个。

在我创建作品的表单中,我有一个字段用于authorName,另一个字段用于clientName:如果作者在作者表中不存在,则会创建它,否则现有的将链接到工作。与客户端相同。为了实现这一点,我使用了first_or_initialize,它运行良好。当我尝试在 update 操作中使用相同的方法时,问题就开始了。这些是我的模型:

工作模式

 class Work < ApplicationRecord

    has_one :description

    belongs_to :author
    belongs_to :client

    accepts_nested_attributes_for :client
    accepts_nested_attributes_for :author

    scope :active, lambda {where(:isActive => true)}
    scope :descOrder, lambda {order(:date => :desc)}
    scope :cover, lambda {where(:isCover => true)}

end 

作者模型

class Author < ApplicationRecord

    has_many :works

end

客户端模型

class Client < ApplicationRecord

    has_many :works

end

快速编辑:您看到的模型与我的应用程序中的完全一样。没有代码被删除。

这是我认为的形式:

<%= form_for(@work, :url => { :controller => "projects", :action => "update"} ) do |f| %>
    <%= f.label("title") %>
    <%= f.text_field(:title) %>

    <%= f.fields_for(:author) do |author| %>
        <%= author.label("author") %>
        <%= author.text_field(:authorName) %>
    <% end %>

    <%= f.fields_for(:client) do |client| %>
        <%= client.label("client") %>
        <%= client.text_field(:clientName) %>
    <% end %>

    <%= f.label("date") %>
    <%= f.date_field(:date) %>


    <%= f.submit("update") %>
<% end %>

这就是我在控制器中处理它的方式:

def edit
  @work = Work.find(params[:id])

  if @work.client.nil?
    @work.build_client
  end

  if @work.author.nil?
    @work.build_author
  end
end

def update
  @work = Work.find(params[:id])

  @work.client = Client.where(clientName: work_params["client_attributes"]["clientName"]).first_or_initialize
  @work.author = Author.where(authorName: work_params["author_attributes"]["authorName"]).first_or_initialize

  if @work.update(work_params)
    flash[:notice] = "work: #{@work.title} updated successfully."
    redirect_to(project_path(@work))
  else
    redirect_to new_project_path
  end
end

private

def work_params
  params.require(:work).permit(:title, :date, client_attributes: [:id, :clientName], author_attributes: [:id, :authorName])
end

这是我得到的错误:

Started PATCH "/projects/21" for ::1 at 2019-10-14 20:00:27 -0700
Processing by ProjectsController#update as HTML
  Parameters: {"authenticity_token"=>"rw3X7VJg8CDnOibniv1jKHTVTGp7pjE4ep6xHpHy0Zp8Xv/0uQd6y5xqq629M2FOOQNoYyOAXH//w5/VoeNEOA==", "work"=>{"title"=>"Progetto1", "author_attributes"=>{"authorName"=>"Autore1", "id"=>"34"}, "client_attributes"=>{"clientName"=>"Cliente4", "id"=>"30"}, "date"=>""}, "commit"=>"update", "id"=>"21"}
  Work Load (0.7ms)  SELECT `works`.* FROM `works` WHERE `works`.`id` = 21 LIMIT 1
  ↳ app/controllers/projects_controller.rb:42:in `update'
  Client Load (0.6ms)  SELECT `clients`.* FROM `clients` WHERE `clients`.`clientName` = 'Cliente4' ORDER BY `clients`.`id` ASC LIMIT 1
  ↳ app/controllers/projects_controller.rb:44:in `update'
  Author Load (0.6ms)  SELECT `authors`.* FROM `authors` WHERE `authors`.`authorName` = 'Autore1' ORDER BY `authors`.`id` ASC LIMIT 1
  ↳ app/controllers/projects_controller.rb:45:in `update'
Completed 404 Not Found in 15ms (ActiveRecord: 1.9ms | Allocations: 3805)



ActiveRecord::RecordNotFound (Couldn't find Client with ID=30 for Work with ID=21):

app/controllers/projects_controller.rb:47:in `update'

即使这些记录 确实 存在于数据库中(具有您在错误中看到的那些 ID)并且它们的外键正确存储在 works 表中(我在 mysql 中检查过)。

我期望实现的行为与 new 操作的行为相同(我在帖子开头所述)。

我该如何解决这个问题?谢谢!


小更新:如果我将first_or_initialize 更改为first_or_create,它确实会创建作者(或客户端),如果不存在,但同时它仍然给我同样的错误。

【问题讨论】:

  • 你不应该把骆驼案和蛇案混在一起。在 Rails 中工作时坚持使用蛇壳;它会让你的生活更轻松。
  • 你能贴出Work Client Author类的完整代码吗?
  • @anothermh 感谢您的建议,我会遵守的。
  • @DimitriusLachi 这些是他们每个人的完整模型,里面没有别的东西,这是一个非常简单的应用程序(另外我想确保在添加任何其他内容之前所有关系都正常工作)跨度>

标签: sql ruby-on-rails ruby database


【解决方案1】:

经过数十次测试,我最终想出了一种解决方案——它并不“优雅”,可能也不是最好的,但至少它可以不间断地工作:

 def edit
    @work = Work.find(params[:id])

    if @work.client.nil?
      @work.build_client
    end 

    if @work.author.nil?
      @work.build_author
    end

  end

  def update
    @work = Work.find(params[:id])

    @work.client = Client.where(clientName: work_params["client_attributes"]["clientName"]).first_or_create
    @work.author = Author.where(authorName: work_params["author_attributes"]["authorName"]).first_or_create

    if @work.update(update_params) 
      flash[:notice] = "work: #{@work.title} updated successfully."
      redirect_to(project_path(@work))
    else
      redirect_to new_project_path
    end

  end

private

    def work_params
      params.require(:work).permit(:title, :date, client_attributes: [:id, :clientName], author_attributes: [:id, :authorName])
    end

    def update_params
      params.require(:work).permit(:title, :date)
    end

由于first_or_initialize 与save 方法一起工作顺利,但它卡住了——至少在我的代码中——用update,我用first_or_create 替换它。

然而,这一次,我使用了另一个私有方法 update_params,它简单地忽略了 :client_attributes 和 :authors_attributes。

正如预期的那样,这会导致Unpermitted parameters: :author_attributes, :client_attributes 错误,但至少所有内容都会通过并得到更新。

老实说,我不太确定我是否完全理解它为什么起作用。但确实如此。

无论如何,如果有人对此问题有更好的解决方案,我完全愿意改进它。

【讨论】:

    猜你喜欢
    • 2013-12-21
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多