【问题标题】:Rails: Use cocoon gem without asset pipelineRails:使用没有资产管道的茧宝石
【发布时间】:2016-09-06 18:02:42
【问题描述】:

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

执行以下操作:

//= require cocoon

不起作用,因为我又不能使用资产管道。

还有其他选择吗?

【问题讨论】:

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


    【解决方案1】:

    您可以在没有茧宝石的情况下制作嵌套表格;

    假设您有一个发票表单,您希望在其中包含客户和产品的嵌套表单。您可以这样做;

    <%= 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 也更改为模型中的任何内容,在此示例中它将变为:&lt;%= f.fields_for :customers do |c| %&gt;

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

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

    【讨论】:

    • 感谢您的回复!虽然我想要 cocoon 的原因是我可以从表单中动态添加和删除字段(利用 link_to_add_association 和 link_to_remove_association)...。我认为没有 cocoon 就没有简单的方法...
    • 您可以使用 jQuery 来做到这一点,这很容易,而且调整自己的代码而不是别人的代码更容易,而且您可以从中学到更多。如果你愿意,我可以教你如何在 jQuery 中做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多