Rails在模型中添加子记录

时间:2014-12-09 16:07:20

标签: ruby-on-rails

我有一个Rails应用程序,其中包含模型:工作人员费用和发票。对于每个发票费用,都有一个invexpense记录。

工作人员可以生孩子。

当我创建发票时,我希望能够从子项中选择要包含在发票上的费用。我希望在发票模型中创建invexpense记录。

发票表单列出了此表中的子费用:

               <% workorder.children.each do |child| %>
                    <% child.expenses.tobill.each do |expense| %>
                        <tr>
                          <td><%= check_box_tag "expense_ids[]", expense.id %></td>
                          <td><%= child.id_desc %></td>
                          <td><%= expense.exp_date %></td>
                          <td><%= expense.description %></td>
                          <td><%= number_to_currency(expense.amount) %></td>
                        </tr>
                    <% end %>
                <% end %>

如果用户检查费用,那么我想创建一个invexpense记录。

再次 - 我正在尝试使用以下代码在发票模型中创建这些记录:

 invexpenses.build  linetype_id: 2, expense_id: expense.id

但是,我不知道如何访问expense_ids[]

我试过的代码:

    if self.expense_ids?
    if expense_ids?
    if expense_ids.count > 0
    if params[:expense_ids] ...

有没有办法从发票表单中访问expense_ids[]

如果应用程序崩溃,我可以在请求参数中看到它们:

screenshot

感谢您的帮助!

PS - 我应该在控制器而不是模型中执行此操作吗?

2 个答案:

答案 0 :(得分:0)

要回答你的上一个问题,是的,params管理应该进入你的控制器。 对于你的表单,我已经使用了simple_form一段时间了,它有一个特定的帮助器。 在这里,从documentation

开始

结构类似于:

class User < ActiveRecord::Base
  belongs_to :company
  has_and_belongs_to_many :roles
end

class Company < ActiveRecord::Base
  has_many :users
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

现在我们有了用户表单:

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.association :company %>
  <%= f.association :roles %>
  <%= f.button :submit %>
<% end %>

之后,在您的控制器中,您可以在children_params哈希:

中像这样访问它
def children_params
  params.require(:children).permit(:whatever, :another_one, expense_ids: [])
end

请注意,这些参数是根据你现在拥有的。

如果您还需要其他任何内容,请随时提出。

答案 1 :(得分:0)

不确定它是最好的答案,但我通过使用Invoice控制器中的代码而不是模型来使其工作:

    newinvexpense = Invexpense.new(
        linetype_id: 2,
        invoice_id: @invoice.id,
        expense_id: params[:expense_ids].first.to_i
    )

以上代码仅适用于数组中的第一个id。我将更新代码以处理数组中的所有ID。