【问题标题】:Updating 2 models at once with same attributes in ruby on rails在 ruby​​ on rails 中一次更新 2 个具有相同属性的模型
【发布时间】:2012-04-30 09:46:48
【问题描述】:

我的 store_opening_stock 表格中有这个

    <%= simple_form_for @store_opening_stock do |f| %>
      <%= f.error_messages %>
      <p>
      <%= f.hidden_field :user_id, :value => current_user.id %>

      <%= f.label :employee_id %>
      <%= f.collection_select :employee_id, Employee.all, :id, :name, options ={:prompt => "-Select  employee  Name"}, :class => "employee name", :style=>'width:210px;'%><br />

         <%= f.label :date %>
        <%= f.datepicker :date, :dateFormat => 'dd MM, yy',  :showOn => "both", :buttonImage => "/assets/calendar.gif", :buttonImageOnly => true, :changeMonth => true, :changeYear => true, :placeholder => "Click on the calender", :yearRange =>'1950:2042' %><br/>

        <%= f.label :product_id %>
        <%= f.collection_select :product_id, Product.all, :id, :title, options ={:prompt => "-Select  Product  Name"}, :class => "product name", :style=>'width:210px;'%><br /> 

        <%= f.input :batch_no,  :label => 'Batch No', :input_html => { :size => 30}%><br/>
        <%= f.input :price,  :label => 'price', :input_html => { :size => 30}, :placeholder =>'Enter Digits'%><br/> 
        <%= f.input :quantity,  :label => 'quantity', :input_html => { :size => 30}, :placeholder =>'Enter Digits'%><br/>
       <p><%= f.submit %></p>
<% end %>

我有两个模型,一个是 store_opening_stock.rb 和 stock.rb

class StoreOpeningStock < ActiveRecord::Base
    attr_accessible :comments_attributes, :stocks_attributes
  attr_accessible :user_id, :date ,:store_location_id, :product_id, :batch_no
  attr_accessible :expiry_date, :price, :quantity, :comment_id, :employee_id
  attr_accessible :goods_receipt_id

  has_many :stocks    
end


class Stock < ActiveRecord::Base
    attr_accessible :date, :store_location_id, :product_id, :batch_no, :expiry_date, :price, :quantity, :goods_reciept_id

    belongs_to :store_opening_stock, :foriegn_key => "store_opening_stock_id"
    acts_as_store_opening_stock
    accepts_nested_attributes_for :store_opening_stocks
end
end

有没有一种方法可以在我单击 store_opening_stock 表单中的提交后立即将 PRICE、PRODUCT_ID、QUANTITY、BATCH-NO 从 store_opening_stocks 更新为库存??????当我在 Ruby on rails 中按下提交时,我可以一次更新 2 个表吗???? 提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 rails-models


    【解决方案1】:

    是的。看到您已经在 stock.rb 模型中使用“accepts_nested_attributes_for”,这是一个很好的做法,同时从库存模型表单中保存多个“store_opening_stock”记录。

    但是如果你想在表单中有不同的模型属性,你可以使用fields_for来做到这一点

    【讨论】:

    • Nimesh 我有点困惑。抱歉,我是框架的新手,确切的字段将如何帮助我用一种形式同时更新两个表中的 price????
    • 请参阅上面的“fields_for”文档链接并向下滚动到与您的要求最相似的“一对多”部分。在表单中插入“库存”模型的价格输入字段后,将在您的数据库中保存 store_opening_stock 时自动创建它们
    • 通过了,非常感谢 Nimesh。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多