【问题标题】:simple_fields_for not showing up [rails 4]simple_fields_for 没有出现 [rails 4]
【发布时间】:2015-01-03 11:43:31
【问题描述】:

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

产品.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

class ProductOption < ActiveRecord::Base
  belongs_to :product
end

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

<%= 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>

【问题讨论】:

    标签: ruby-on-rails nested-attributes hidden-field


    【解决方案1】:

    我想通了,...问题是

    fields_for 将遍历集合关联,渲染出与其中的项目一样多的次数,这意味着如果关联为空则为 0 次

    所以要解决我必须添加的问题

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

    到控制器中的索引操作。

    【讨论】:

    • 感谢您为后代留下答案。它帮助了我!
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多