加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails:使用一个表单和一个提交为多个

发布时间:2020-12-16 19:04:57 所属栏目:百科 来源:网络整理
导读:我有3个型号:报价,客户和项目.每个报价都有一个客户和一个项目.当我按下提交按钮时,我想在各自的表格中创建新报价,新客户和新项目.我已经查看了其他问题和轨道广播,要么它们不适用于我的情况,要么我不知道如何实现它们. quote.rb class Quote ActiveRecord:
我有3个型号:报价,客户和项目.每个报价都有一个客户和一个项目.当我按下提交按钮时,我想在各自的表格中创建新报价,新客户和新项目.我已经查看了其他问题和轨道广播,要么它们不适用于我的情况,要么我不知道如何实现它们.

quote.rb

class Quote < ActiveRecord::Base
  attr_accessible :quote_number
  has_one :customer
  has_one :item
end

customer.rb

class Customer < ActiveRecord::Base
  attr_accessible :firstname,:lastname
  #unsure of what to put here
  #a customer can have multiple quotes,so would i use has_many or belongs_to?
  belongs_to :quote
end

item.rb的

class Item < ActiveRecord::Base
  attr_accessible :name,:description
  #also unsure about this
  #each item can also be in multiple quotes
  belongs_to :quote

quotes_controller.rb

class QuotesController < ApplicationController
  def index
    @quote = Quote.new
    @customer = Customer.new
    @item = item.new
  end

  def create
    @quote = Quote.new(params[:quote])
    @quote.save
    @customer = Customer.new(params[:customer])
    @customer.save
    @item = Item.new(params[:item])
    @item.save
  end
end

items_controller.rb

class ItemsController < ApplicationController
  def index
  end

  def new
    @item = Item.new
  end

  def create
    @item = Item.new(params[:item])
    @item.save
  end
end

customers_controller.rb

class CustomersController < ApplicationController
  def index
  end

  def new
    @customer = Customer.new
  end

  def create
    @customer = Customer.new(params[:customer])
    @customer.save
  end
end

我的报价单/ new.html.erb

<%= form_for @quote do |f| %>
  <%= f.fields_for @customer do |builder| %>
    <%= label_tag :firstname %>
    <%= builder.text_field :firstname %>
    <%= label_tag :lastname %>
    <%= builder.text_field :lastname %>
  <% end %>
  <%= f.fields_for @item do |builder| %>
    <%= label_tag :name %>
    <%= builder.text_field :name %>
    <%= label_tag :description %>
    <%= builder.text_field :description %>
  <% end %>
  <%= label_tag :quote_number %>
  <%= f.text_field :quote_number %>
  <%= f.submit %>
<% end %>

当我尝试提交时,我收到错误:

Can't mass-assign protected attributes: item,customer

所以为了尝试修复它我更新了quote.rb中的attr_accessible以包含:item,:customer但是我得到了这个错误:

Item(#) expected,got ActiveSupport::HashWithIndifferentAccess(#)

任何帮助将不胜感激.

解决方法

要提交表单及其相关的子项,您需要使用 accepts_nested_attributes_for

要做到这一点,你需要在你将要使用的控制器的模型中声明它(在你的情况下,它看起来像Quote Controller.

class Quote < ActiveRecord::Base
  attr_accessible :quote_number
  has_one :customer
  has_one :item
  accepts_nested_attributes_for :customers,:items
end

此外,您需要确保声明哪个attributes are accessible以避免其他质量分配错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读