jjzjj

铁轨5-嵌套属性的强参数

程序员大本营 2024-05-28 原文

我很难为模型构造嵌套属性 要求.

数据以正确的方式通过我的后行动传递。

白名单这些参数我缺少什么?

感谢任何帮助。

控制台输出

Started POST "/requests" for 127.0.0.1 at 2017-06-08 10:57:15 -0400Processing by RequestsController#create as HTML  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fmvhoPxVpcHoqOd32mO/HJMrfaPUd+KbNqDJiSRs78U44Y0uL3prpTfU6wmw7PAwv0b+mRHXOGMLvD9bsZpxnw==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"[email protected]", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"[email protected]", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"56", "table_location_ids"=>["1"], "drink_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}], "chaser_ids"=>["1"], "comments"=>""}, "commit"=>"Submit"}Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)ActiveModel::UnknownAttributeError (unknown attribute 'drink_attributes' for Request.):

app/models/request.rb

class Request < ApplicationRecord    has_many :request_drinks    has_many :drinks, through: :request_drinks    accepts_nested_attributes_for :drinksend

应用程序/型号/饮料

class Drink < ApplicationRecord    has_many :request_drinks    has_many :requests, through: :request_drinksend

app/model/request_drink.rb

class RequestDrink < ApplicationRecord    belongs_to :request    belongs_to :drinkend

app/controllers/request_controller.rb

class RequestsController < ApplicationController  before_action :set_request, only: [:show,                                     :edit,                                     :update,                                     :destroy]  def index    @requests = Request.search(params[:term], params[:filter], params[:page])  end  def show  end  def new    @request = Request.new    @drinks = Drink.active  end  def edit  end  def create    @request = Request.new(request_params)    respond_to do |format|      if @request.save        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }        format.json { render :show, status: :created, location: @request }      else        format.html { render :new }        format.json { render json: @request.errors, status: :unprocessable_entity }      end    end  end  def update    respond_to do |format|      if @request.update(request_params)        format.html { redirect_to @request, notice: 'Request was successfully updated.' }        format.json { render :show, status: :ok, location: @request }      else        format.html { render :edit }        format.json { render json: @request.errors, status: :unprocessable_entity }      end    end  end  def destroy    @request.destroy    respond_to do |format|      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }      format.json { head :no_content }    end  end  private    def set_request      @request = Request.find(params[:id])    end    def request_params      params.require(:request).permit(:concierge_name,                                      :concierge_number,                                      :concierge_email,                                      :client_name,                                      :client_number,                                      :client_email,                                      :hotel_employee,                                      :concierge_service,                                      :vip_promoter,                                      :arriving_with_client,                                      :client_alone,                                      :people,                                      :males,                                      :females,                                      :table_minimum,                                      :arrival_time,                                      :comments,                                      :drink_attributes => [:id, :quantity]      )    endend

app/views/requests/_form.html.erb

...    <div class="field-3">      <h4>Drinks</h4>      <% @drinks.all.each do |d| %>        <%= hidden_field_tag "request[drink_attributes][][id]", d.id %>        <%= number_field_tag "request[drink_attributes][][quantity]" %>        <%= d.name %>        <br />      <% end %>    </div>...

看答案

您需要使用对象的复数形式(即 drinks)使用时 嵌套属性.

所以,在你的 request_params 改变:

:drink_attributes => [:id, :quantity]

至:

:drinks_attributes => [:id, :quantity]

您也需要更新表格:

...  <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>  <%= number_field_tag "request[drinks_attributes][][quantity]" %>...

有关铁轨5-嵌套属性的强参数的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  3. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  5. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  6. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  7. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  8. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  9. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  10. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

随机推荐