simple_fields_for不显示[rails 4] [英] simple_fields_for not showing up [rails 4]

查看:69
本文介绍了simple_fields_for不显示[rails 4]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建两个隐藏字段,一个显示没有问题,但是另一个来自嵌套表单的

Im trying to create two hidden fields, and one shows up no problem, but the other that comes from the nested form does not

product.rb

product.rb

class Product < ActiveRecord::Base
  has_many :product_options,  dependent: :destroy
  accepts_nested_attributes_for :product_options, allow_destroy: true, :reject_if => proc { |x| x[:option_name].blank? }
  belongs_to :user
end 

product_option.rb

product_option.rb

class ProductOption < ActiveRecord::Base
  belongs_to :product
end

products_controller.rb

products_controller.rb

class ProductsController < ActionController::Base
  layout "application"

  def index 
    @products = Product.all
    @current_user = Client.find_by(id: session[:client])
    if @current_user.redeemed == true 
      redirect_to root_path
    end
  end 

  def show
    @product = Product.find(params[:id])
    @product_option = @product.product_options.find(params[:id])
    @current_user = Client.find_by(id: session[:client])
    @current_user.update(:product_option => @product_option.option_name)
    @current_user.update(:selected_product => @product.id)
    render :nothing => true
  end

  private
    def product_params
      params.require(:product).permit(:name, :id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id, 
          :product_options_attributes => [:id, :option_name, :ranking, :total_redeemed, :product_id])
    end
end

_form.html.erb

_form.html.erb

<%= simple_form_for Product.new, :method => "post",:remote => true, :class => "item_prompt" do |f| %> 
      <%= f.hidden_field :id, :class => 'product_id' %>
        <%= f.simple_fields_for :product_options do |ff| %>
          <%= ff.hidden_field :id, :class => 'product_option_id' %>
        <% end %>
      <%= f.submit "Yep!", :class => "yep ready_button confirm_button", :name => "confirm_button" %>
    <% end %>

html输出

<form accept-charset="UTF-8" action="/products" class="simple_form new_product" data-remote="true" id="new_product" method="post" novalidate="novalidate">
  <input class="product_id" id="product_id" name="id" type="hidden" value="240">
  <input class="yep ready_button confirm_button" name="confirm_button" type="submit" value="Yep!">
<form>

推荐答案

我知道了,...问题出在

I figured this out, ... the problem was

fields_for将遍历一个集合关联,渲染次数与其中的项目数相同,如果该关联为空,则表示为0次

fields_for will loop over a collection association, rendering out as many times as there are items in it, which means 0 times if the association is empty

所以要解决我不得不添加的问题

so to fix the problem I had to add

@product = Product.new
@product.product_options.build

到控制器中的索引动作.

to the index action in the controller.

这篇关于simple_fields_for不显示[rails 4]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆