Rails:使用没有资产管道的cocoon gem

时间:2016-09-06 18:02:42

标签: ruby-on-rails ruby-on-rails-3 asset-pipeline redmine redmine-plugins

我在Rails for Redmine中编写了一个插件,这是一个不支持资产管道的应用程序。有什么方法可以使用cocoon gem,但不使用资产管道?我的Rails版本是3.2.21

执行以下操作:

//= require cocoon

不起作用,因为我再也无法使用资产管道。

还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

您可以制作没有cocoon gem的嵌套表单;

我们假设您有一张发票表单,您希望在其中包含客户和产品的嵌套表单。您可以执行此操作;

<%= form_for @invoice do |f| %>

 <%= f.text_field :invoice_number %>

 <%= f.fields_for :customer do |c| %> // start nested form
  <%= c.label 'customer name' %>
  <%= c.text_field :customer_name %>
 <% end %>

 <%= f.fields_for :products do |p| %> // start nested form 
  <%= p.label 'product name' %>
  <%= p.label :product_name %>
 <% end %>

<%= f.submit 'save invoice', invoices_path, class: 'btn btn-primary' %>

<% end %>

在发票型号中执行:

  has_one :customer
  has_many :products

  accepts_nested_attributes_for :customer, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true

客户模式

  belongs_to :invoice

产品型号

  belongs_to :invoice

在你的控制器中:

def invoice_params
  params.require(:invoice).permit(:number customer_attributes: [:id, :customer_name :_destroy],  products_attributes: [:id, :product_name])
end

我使用发票作为解释,但您可以使用您拥有的任何模型/关系进行更改。但请记住遵循相同的复数术语。例如,如果您的模型中有has_many :customers而不是has_one :customer,请记得将接受嵌套属性更改为accepts_nested_attributes_for :customers,并在控制器中将customer_attributes: [:id, :customer_name :_destroy]更改为customers_attributes: [:id, :customer_name :_destroy]

最后但并非最不重要的是记得将f.fields_for更改为模型中的任何内容,在此示例中它将成为:<%= f.fields_for :customers do |c| %>

修改 在某些情况下,您必须在控制器中创建实例。在控制器的新操作中,您必须执行以下操作:

  def index
    @invoices = Invoice.all
  end


  # GET /invoices/new
  def new
    @invoice = Invoice.new
    @invoice.products.build
    @invoice.build_customer

  end