【问题标题】:Select Tag, Options_from_collection_for_select determine correct id for selected选择标签,Options_from_collection_for_select 确定选择的正确 id
【发布时间】:2018-04-11 01:29:46
【问题描述】:

我有以下表格:

<% tb_form_for [:location] do |f| %>
 <%= f.tb_text_field :name %>
 <%= f.tb_number_field :postal_code %>
 <%= f.tb_text_field :phone %>
 <%= tb_select :region_id, options_from_collection_for_select(Region.all, :id, :name, :region_id)%>
 <% end %>

我了解选择集合中选项的细分。位置一为集合,位置二为值,位置三为文本方法,位置为选中。前三个职位工作正常,这是我无法完成的工作。

例如,如果我有一个 ID 为 4 的芝加哥位置。它的伊利诺伊州区域为 6。当我去编辑表单而不是看到伊利诺伊州时,我看到的是加利福尼亚州(其 ID 为 4)。

我已经尝试过选择:

  • :region_id 这显示了集合中的第一个
  • :id 这显示了集合中的第一个
  • params[:id] 这会拉取位置的 id 并拉取具有 THAT id 的区域
  • params[:region_id] 这显示了集合中的第一个

我错过了什么吗?

区域有_许多位置。位置属于_to 地区。区域控制器看起来像:

class Admin::RegionsController < Admin::ApplicationController
 belongs_to_app :regions
  add_breadcrumb 'Regions', :admin_regions_path
  before_action :load_region, only: [:show, :edit, :update, :destroy]

  def index
    @regions = Region.ordered.paginate(page: params[:page])
    @regions = @regions.search(params[:search]) if params[:search]
    respond_with @regions
  end

  def show
    respond_with @region
  end

  def new
    @region = Region.new
    respond_with @region
  end

  def create
    operation = Region::Create.run(region_params)
    flash[:notice] = 'Region created successfully' if operation.success
    respond_with operation.result, location: admin_regions_path
  end

  def edit
    respond_with @region
  end

  def update
    flash[:notice] = 'Region updated successfully' if @region.update_attributes(region_params)
    respond_with @region, location: admin_regions_path
  end

  def destroy
    flash[:notice] = 'Region deleted successfully' if @region.destroy
    respond_with @region, location: admin_regions_path
  end

  private

  def load_region
    @region = Region.find_by!(id: params[:id])
  end

  def region_params
    params.require(:region).permit(:name, :description, :youtube_url,
  :url_name, :staff_photo, :group_photo,
  location_ids: [])
  end
end

【问题讨论】:

  • 这是如何关联的?
  • 我会更新问题。

标签: ruby-on-rails


【解决方案1】:

我觉得自己像个白痴。位置拉入区域 id,所以我只需要引用位置上的 id。所以答案其实是:

<%= tb_select :region_id, options_from_collection_for_select(Region.all, :id, :name, @location.region_id)%>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多