Как сохранить более одной записи для одного идентификатора в одной таблице? - PullRequest
0 голосов
/ 26 февраля 2012

У меня есть две таблицы salary_structures и payheads. Ниже приведены структуры моей таблицы:

create_table "payheads", :force => true do |t|
    t.integer  "company_id",             :null => false
    t.integer  "defined_by",             :null => false
    t.string   "payhead_type"
    t.string   "payhead_name"
    t.string   "under"
    t.string   "affect_net_salary"
    t.string   "name_appear_in_payslip"
    t.string   "use_of_gratuity"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

и

create_table "salary_structures", :force => true do |t|
    t.integer  "company_id",                                                          :null => false
    t.integer  "for_employee"
    t.integer  "created_by"
    t.date     "effective_from_date"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "payhead_id"
    t.decimal  "amount",              :precision => 18, :scale => 2, :default => 0.0
  end

В соответствии с моей структурой таблицы у меня есть payhead_id в моей таблице salary_structures, а в моей таблице - у меня четыре выплаты (базовая, Pf и т. Д.). Теперь, когда администратор хочет определить salary_structure сотрудника, он должен установить сумму для каждой выплаты, в соответствии с моим дизайном, я хочу сохранить все выплаты для сотрудника для одной salary_structure сразу. Но здесь проблема заключается в одном идентификаторе salary_structure Как я могу сохранить более чем одну выплату. Ниже моя форма просмотра:

<%= form_for(@salary_structure) do |f| %>
   <%= render 'shared/form_error', :object => @salary_structure %>

        <div class="field">
             <%= f.label :for_employee, :class => "required" %><br />
             <%= collection_select(:salary_structure, :for_employee, @users, :id, :first_name,:autofocus =>"autofocus", :prompt => true) %>
          </div>

     <div class="column width3">
            <div class="field">
             <%= f.label :effective_from_date, :class => "required" %><br />
             <%= f.text_field :effective_from_date %>
          </div>
     </div> 
     <div class="column width6 first">
      <table  class=" display stylized full" id="salary_structure_report" style="">
         <thead>
            <tr>
             <th width="80%"><label class="required">Pay Head</label></th>
             <th width = "20%"><label class="required">Amount</label></th>
            </tr>
         </thead>
             <tbody>
                <% for ph in @payheads %>
                  <tr>
                    <td width = "80%">
                        <%= f.hidden_field "payhead_id", ph.id %>
                        <%= ph.payhead_name %> </td>
                    <td width = "20%" ><%= f.text_field :amount %></td>
                  </tr>
                <% end %>
                </tbody>
                <tfoot>
                  <tr>
                   <td class="ta-right" width = "80%">Total</td>
                   <td class="ta-left" width = "20%"><span class="WebRupee">Rs</span><span id = "total">00.00</span></td>
                  </tr>
                 </tfoot>
      </table>
   </div><br />
       <div class = "column width3 first">


              <button type="submit" class="btn btn-green big"><img src="/images/add.png" class="icon" /> Save</button>&nbsp;

            <%= link_to 'Cancel', salary_structures_path, :class=>"btn btn-gray bg"%>
       </div>
   </div>  
<% end %>

Когда я пытался сохранить его как обычно, он не сохраняет идентификатор оплаты в таблице salary_structures Должен ли я сделать что-то в моделях. Любая помощь, буду извиняться, спасибо заранее.

Ответы [ 2 ]

1 голос
/ 27 февраля 2012
app/models/payhead.rb

  belongs_to :salary_structure

app/models/salary_structure.rb

  has_many :payheads

db/migration/create_payheads.rb

  create_table 'payheads', :force => true do |t|
    # define other columns
    t.integer salary_structure_id
  end

db/migration/create_salary_structure.rb

  # remove t.integer payhead_id

получить доступ друг к другу,

Payhead.find(some_payhead_id).salary_structure

или

SalaryStructure.find(some_salary_structure_id).payheads

создать новую выплату для существующей salary_structure,

SalaryStructure.find(some_salary_structure_id).payheads.create(params[:payhead])
# params[:payhead] is part of the form data
0 голосов
/ 27 февраля 2012

Привет, друзья! Я нашел новый способ решить эту проблему, используя другую таблицу с именем "line_item", и использовал ".build" в моем контроллере, и это как-то работает.В своей форме я использовал вложенную форму.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...