如何在 rails 6 中更新 @model.submodel [英] How to update @model.submodel in rails 6

查看:47
本文介绍了如何在 rails 6 中更新 @model.submodel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试更新子模型失败,以某种方式嵌套但得到异常结果.

背景(向下滚动问题):

更新reviews 模型的布尔值verified 以将翻译是否经过验证与翻译entryuser 相关联 模型关联的引用.有关创建验证的详细信息位于

但不是

{_method"=>patch",authenticity_token"=>...",审查"=>{已验证"=>0"},提交"=>更新审查"}

解决方案

我想我在@yzalavin 建议后发现了问题.不知何故,验证阻止了更新.我还不知道这个协会.

只需添加 on::create 就可以让我更新.

validates_presence_of :entry_id, :user_id, :verified, on: :create

I'm unsuccessfully trying to update a submodel, somehow nested but getting unusual results.

Background (Scroll down for problem):

Update a boolean verified of a reviews model to associate whether a translation is verified or not, with translation entry and user model associated references. Details about creating a verification are here

# routes.rb
resources :entries do
   resources :reviews
end


# entry.rb
belongs_to :user
has_one :review
accepts_nested_attributes_for :review


# user.rb
has_many :entries
has_many :reviews


# review.rb
belongs_to :user
belongs_to :entry

From entry index, pass the entry instance to the edit partial, works perfect

# /entries/index.html.erb
<% @entries.each do |entry| %>
   ...
   <% if entry.review %>
      <%= render 'reviews/edit', entry: entry %>
   <% end %>
   ...
<% end %>

The _edit.html.erb form seems correct...

# reviews/_edit.html.erb
<span>
  <%= form_for([entry, entry.review]) do |f| %>
    <div class="form-check form-switch">
      <%= f.check_box :verified, class: "form-check-input" %>
    </div>
    <%= f.submit class: "btn btn-primary"%>
  <% end %>
</span>

In the browser console, the model entry is well assigned. And also the association entry.review is well assigned i.e

>> entry.review
=> #<Review id: 4, user_id: 1, entry_id: 19, 
     verified: false, created_at: "2021-02-18 03:43:27", 
     updated_at: "2021-02-18 14:31:15">

Even using the Ruby on Rails 6 deprecated method update_attribute works

>> entry.review.update_attribute(:verified, false)
=> true


Problem: The update method in reviews_controller.rb executes successfully when verified is true, but not when it's false

# reviews_controller.rb
def update
   @entry.review.update(review_params)
end

private

def review_params
   params.require(:review).permit(:verified, user: current_user, entry: @entry)
end

Works

{"_method"=>"patch", "authenticity_token"=>"...", 
"review"=>{"verified"=>"1"}, "commit"=>"Update Review"}

but not

{"_method"=>"patch", "authenticity_token"=>"...", 
"review"=>{"verified"=>"0"}, "commit"=>"Update Review"}

解决方案

I think I found the problem after @yzalavin suggestion. Somehow validations were preventing the update. I do not know the association yet.

Simply adding on: :create allowed me o update.

validates_presence_of :entry_id, :user_id, :verified, on: :create

这篇关于如何在 rails 6 中更新 @model.submodel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆