Rails 无法获取 collection_select 以分配父模型 ID,但 fields_for 可用于嵌套表单

问题描述

首先,我对 Rails 很陌生:) 我试图让我的用户选择从 collect_select 下拉列表中选择一个城市(父模型),或者,如果他们想要的城市不存在,则创建一个新城市。我的表单中的 fields_for 有效,并且两者在他们的显示页面上清楚地相关联......但是每当我尝试使用它而不是创建一个新城市时,集合选择就会抛出一个错误“城市必须存在”。他们在同一个表格上。我在这一点上迷路了,所以我很感激任何指导:

餐厅模型

  belongs_to :user
  belongs_to :city
  has_many :recommendations
  accepts_nested_attributes_for :city,reject_if: :all_blank
  validates :name,presence: true
  validates :additional_info,length: {minimum: 5,maximum: 200},allow_blank: true
  # validates :city_id,presence: true
  # validates_associated :city

  # def city_name
  #   self.try(:city).try(:name)
  # end

  def city_attributes=(attributes)
    city = City.find_or_create_by(attributes)
    self.city = city if city.valid? || self.city
  end
end

城市模型

    has_many :restaurants
    has_many :users,through: :restaurants
    accepts_nested_attributes_for :restaurants,reject_if: :all_blank
    validates :name,presence: true,uniqueness: true
    validates :state_or_country,length: {minimum: 3,maximum: 25},allow_blank: true
    validates :airport_code,length: {is: 3},allow_blank: true
end

新餐厅形式


<h1> Add a new restaurant! </h1>

<%= form_for @restaurant do |f| %>
  <p>
    <%= f.label :name %>
    <%= f.text_field :name %><br>
    <div>
    </div>
    <%= f.label :hours%>
    <%= f.text_field :hours%>
    <div>
    </div>
    <%=f.label :discount%>
    <%= f.text_field :discount%>
    <div>
    </div>
    <%=f.label :additional_info%>
    <%= f.text_field :additional_info%>
    <div>
    </div>
      Long or short layover?
    <div>
    </div>
      <%= f.select :long_or_short_layover,['Long','Short']%>
    <div>
    </div>
      <%= f.select :price_point,['Newhire Pay','Ten Year Pay','Topout Pay']%>
    <div>
    </div>
      <label for="city_id">Select a city:</label>
      <%= f.collection_select :city_id,City.all,:id,:name,prompt: true %>
      <%= f.hidden_field :city_id %>
    <div>
    </div>
    <% if !params[:city_id] %>
    <%= f.fields_for :city,@restaurant.build_city do  |cf|%>
        <h2>Or create a new city:</h2>
        <%= cf.label :name %>
        <%= cf.text_field :name %>
        <% end %> 
    <% end %> 
    <div>
    </div>
    <%= f.submit %>
  </p>
<% end %> 

餐厅管理员

     before_action :redirect_if_not_logged_in?
    #  before_action :set_city,only: [:new,:create]


  def new
    # @restaurant = Restaurant.new
    # @restaurant.build_city
      if params[:city_id] && !City.exists?(params[:city_id])
        redirect_to citys_path,alert: "city not found"
      else
        @restaurant = Restaurant.new(city_id: params[:city_id])
      end
  end 

  def create
    @restaurant = current_user.restaurants.new(restaurant_params)
  #@restaurant = current_user.restaurants.build(restaurant_params)
  #@restaurant = current_user.Restaurant.build(restaurant_params)
    if @restaurant.save!
      flash[:notice] = "restaurant saved!"
      redirect_to restaurant_path(@restaurant)
    end 
  end

  def index
      if params[:city_id]
         @city = City.find_by(id: params[:city_id])
            if @city.nil?
              redirect_to cities_path,alert: "city not found"
            else
              @restaurants = @city.restaurants
            end
        else
            @restaurants = Restaurant.all
        end
    end 

  def show
      if params[:city_id]
         @city = City.find_by(id: params[:city_id])
         @restaurant = @city.restaurants.find_by(id: params[:id])
            if @restaurant.nil?
               redirect_to city_restaurants_path(@city),alert: "restaurant not found"
            end
      else
         @restaurant = Restaurant.find(params[:id])
      end
  end

    def edit
        if params[:city_id]
           city = City.find_by(id: params[:city_id])
           if city.nil?
              redirect_to cities_path,alert: "city not found"
           else
              @restaurant = city.restaurants.find_by(id: params[:id])
              redirect_to city_restaurants_path(city),alert: "restaurant not found" if @restaurant.nil?
        end
           else
              @restaurant = Restaurant.find(params[:id])
        end
    end

    def update
        @restaurant = Restaurant.find(params[:id])
        @restaurant.update(restaurant_params)
          if @restaurant.save
             redirect_to @restaurant
          else
             render :edit
          end
     end

    def destroy
        @restaurant = Restaurant.find_by_id(params[:id]).destroy
        #@restaurant.destroy
          if @restaurant.destroy!
             flash[:notice] = "Okay,its gone!"
             redirect_to restaurants_path
          else
             render :show
          end 
    end

private

    # def set_city
    #     @city = City.find_by(id: params[:city_id])
    # end

  
    def restaurant_params
        params.require(:restaurant).permit(:name,:hours,:long_or_short_layover,:price_point,:discount,:additional_info,:city_id,:user_id,city_attributes: [:name])
    end
end```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...