options_for_select 在 simple_form

options_for_select on simple_form

我可能用错了,想不通。

我正在 simple_form 上使用 options_for_select。它呈现良好且没有错误,但所选选项不会保存到数据库中。所有其他字段保存没有问题。

select_tag是

<%= select_tag :experiment_type, options_for_select(['AOV', 'Conversion']), :prompt => "Select a Project Type" %>  

控制器:

class ExperimentsController < ApplicationController
    before_action :find_advertiser
    before_action :find_experiment, only: [:edit, :update, :show, :destroy]


    def index
        @experiments = Experiment.all.order("created_at DESC")
    end

    def show

    end

    def new
        @experiment = Experiment.new
        @advertisers = Advertiser.all.map{ |c| [c.name, c.id] }

    end

    def create
        @experiment = Experiment.new(experiment_params)
        @experiment.advertiser_id = params[:advertiser_id]   

        if @experiment.save
             redirect_to advertiser_path(@advertiser)
        else
            render 'new'
        end
    end

    def edit
            @projects = Project.all.map{ |c| [c.name, c.id] }
    end

    def update
        @experiment.advertiser_id = params[:id]     
        if @experiment.update(experiment_params)
            redirect_to experiment_path(@experiment)
        else
            render 'edit'
        end
    end

    def destroy
        @experiment.destroy
        redirect_to root_path
    end

private

    def experiment_params
        params.require(:experiment).permit(:advertiser_id, :name, :experiment_type, :hypothesis, :priority, :status, :launch_date, 
            :description, :baseline_url, :test_url, :baseline_aov_60, :baseline_aov_30, :baseline_aov_mtd,
            :baseline_conversion_60, :baseline_conversion_30, :baseline_conversion_mtd)
    end

    def find_advertiser
        @advertiser = Advertiser.find(params[:advertiser_id])
    end

    def find_experiment
        @experiment = Experiment.find(params[:id])
    end
end

我需要你的完整表单布局才能确定地告诉你,但根据你的 experiment_params 方法,experiment_type 字段是实验的一部分。但是,当您仅使用 select_tag 时,它不会连接到您的主要对象。您只需要使用 select。类似这样:

<%= simple_form_for :experiment do |f| %>
...
<%= f.select ... %>
...
<% end %>

或在 simple_form format:

<%= f.input :experiment_type, collection: ['AOV', 'Conversion'] %>

我的猜测也是基于你的哈希:

"experiment_type"=>"AOV", "experiment"=>{"name"=>"Test" ....

experiment_type 在你的 "experiment" 之外。