1

我正在Rails for Redmine中编写插件,这是一个不支持资产管道的应用程序。有什么方法可以使用茧宝石,但不使用资产管道?我的Rails的版本是3.2.21Rails:在没有资产管道的情况下使用茧宝石

执行以下操作:

//= require cocoon 

不起作用,因为,再一次,我不能用资产的管道。

有没有其他的选择?

回答

0

您可以制作没有茧宝石的嵌套窗体;

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

<%= 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_one :customerhas_many :customers记得改接受嵌套属性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 
+0

感谢您的回复!虽然我想茧的原因是我可以动态添加和删除我的表单中的字段(利用link_to_add_association和link_to_remove_association)....我看到没有无琐事的方式来做到这一点没有茧... – ineedahero

+0

你可以使用jQuery来做到这一点,这很容易,而且更容易调整自己的代码而不是别人,再加上你从中学到更多东西。如果你想我可以教你如何在jQuery中做到这一点。 – luissimo

相关问题