更新Rails中的字段

时间:2018-07-06 01:16:10

标签: ruby-on-rails ruby ruby-on-rails-5

我有一个父母表,一个孩子和一个供款表。子表具有parent_id,资金表具有child_id。父母为孩子申请各种活动的资金。每个孩子可以有多个资助申请。儿童表中的amount_remaining字段默认为每个儿童$ 400。在资金表中,有一个用于活动的字段amount_requested。一旦将资金表中的状态字段更改为已批准,就从特定孩子的剩余金额中减去所请求的金额。这怎么可能。请帮我。我尝试了以下步骤,但不起作用。

child.rb

after_save do
        if status_changed? && status == 'Approved'
          amount_remaining = child.amount_remaining - funding.amount_requested
          child.update_attributes(amount_remaining: amount_remaining)
        end
    end

筹资方式表

create_table "fundings", force: :cascade do |t|
    t.string "type_of_activity"
    t.integer "amount_requested"
    t.integer "child_id"
    t.string "status"
end

儿童桌模式

create_table "children", force: :cascade do |t|
    t.string "firstname"
    t.string "lastname"
    t.integer "parent_id"
    t.integer "amount_remaining"
end

_form.html.erb(注资申请表)

<div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :amount_requested, class: "required" %>
        </div>
        <div class="col-sm-8">
          <%= form.text_field :amount_requested, required: true %>
        </div>
      </div> 
      <div class = "form-group">
        <div class="control-label col-sm-2">
          <%= form.label :status %>
        </div>
      <% if current_user.superadmin? %>
        <div class="col-sm-8">
          <%= form.select :status,['Pending', 'Approved', 'Declined'], {}, id: "sample-status-select", class: "form-control" %>
        </div>
      <% else %>
        <div class="col-sm-8">
          <%= form.select :status,['Pending', 'Approved', 'Declined'], {class: "form-control"}, {:disabled => true} %>
        </div>
      </div>
      <% end %>

1 个答案:

答案 0 :(得分:0)

child_id模型中有Funding

funding.rb

   belongs_to :child

    after_save do
      if status_changed? && status == 'Approved'
        if child.amount_remaining.to_f > funding.amount_requested.to_f
          amount_remaining = child.amount_remaining - funding.amount_requested
          child.update_column(:amount_remaining, amount_remaining)
        else
          errors.add(:insufficient_amount, "Insufficient amount!")
          raise ActiveRecord::RecordInvalid.new(self)
        end
      end
    end

仅当approve时,您应该child.amount_remaining.to_f > funding.amount_requested.to_f资助。