HABTM - 添加和删除按钮(在节目视图中)

时间:2014-03-05 09:20:21

标签: ruby-on-rails simple-form has-and-belongs-to-many

我正在显示一张发票,我想要添加'fly'产品。我想使用产品的下拉框和添加按钮来执行此操作。将产品添加到发票后,我希望能够单击删除按钮将其删除。

我目前通过控制台进行此操作,但我不确定如何在前端执行此操作。

如何设置::

用户模型:

class User < ActiveRecord::Base

....
has_many :invoices
....
end

发票型号:

class Invoice < ActiveRecord::Base
  attr_accessible :active
  validates :user_id, presence: true
  belongs_to :user

  has_many :categorizations
  has_many :flies, through: :categorizations
end

发票迁移:

class CreateInvoices < ActiveRecord::Migration
  def change
    create_table :invoices do |t|
      t.boolean :active
      t.integer :user_id

      t.timestamps
    end
    add_index :invoices, :user_id
  end

end

分类模型:

class Categorization < ActiveRecord::Base
  attr_accessible :fly_id, :user_id

  belongs_to :invoice
  belongs_to :fly
end

分类迁移:

class CreateCategorizations < ActiveRecord::Migration
  def change
    create_table :categorizations do |t|
      t.integer :user_id
      t.integer :fly_id

      t.timestamps

      add_index :categorizations, :user_id
      add_index :categorizations, :fly_id
    end
  end
end

飞行模型:

class Fly < ActiveRecord::Base
  attr_accessible :description, :name
  validates :description, :name, presence: true

  has_many :categorizations
  has_many :invoices, through: :categorizations
end

飞行迁移:

class CreateFlies < ActiveRecord::Migration
  def change
    create_table :flies do |t|
      t.string :name
      t.string :description

      t.timestamps
    end
  end
end

显示发票视图:

<h3>Invoice</h3>
<p>User Name:
  <%= @invoice.user.name %></p>
<p>
  Invoice ID:
  <%= @invoice.id %></p>
<p>
  Invoice Active?:
  <%= check_box_tag 'admin', '1', @invoice.active, :disabled => true %></p>
<p>Email:
  <%= @invoice.user.email if @invoice.user.email %></p>
<table class="table table-condensed">
  <thead>
    <tr>
      <th>Invoice Flies</th>
    </thead>
    <tbody>
      <% @invoice.flies.each do |fly| %>
        <tr>
          <td><%= fly.name %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

  <%= simple_form_for(@categorization) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

#this is where I want to add my 'add product to invoice' functionality


      <%= f.submit "Add Fly to Invoice", class: "btn btn-large btn-primary" %>
    <% end %>


  <%= button_to "Mark as Sent", {:controller => :invoices, :action => :activate, :id => @invoice.id }, {:method => :post } %>
<%= button_to "Mark as not sent", {:controller => :invoices, :action => :deactivate, :id => @invoice.id }, {:method => :post } %>
<br><br>
  <%= link_to "Back to list of invoices", invoices_path %>

1 个答案:

答案 0 :(得分:0)