Rails 4,简单形式:自定义URL无法正确查找用户ID

时间:2015-12-12 13:10:28

标签: ruby-on-rails simple-form

我有一个bsic问题,重新定义了一个simple_form

这是表格

  <%= simple_form_for(current_user, :url =>  nation_user_path(current_user), :method => :post) do |f| %>
        <%= f.input :selected_country, collection: @user_country_array, label: "Select a country to view data on (only countries represented are listed)", class: 'form-control' %>
        <%= f.submit "Submit", class: "btn btn-primary" %></h3>
  <% end %>

的routes.rb

resources :users do
   member do
     get :network
     post :nation
   end
end

user_controller

before_action :set_user, only: [:show, :edit, :update, :destroy, :nation]


 def nation
    @country = User.find(params[:user][:selected_country])
    @user_country_array = Array.new
    @user_country_array = User.all.map {|user| user.country }.reject{ |country| country.nil? }.uniq.sort
    @user_count = User.all.select { |u| u.user_complete == true }.count
    @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.to_s.downcase]}.map {|c, v | ["code" => c, "value" => v, "flag" => c.to_s.downcase]}.flatten.to_json
    @sectiona =  User.all.group('practice').count.map { |k,v| [ "name" => k, "y" => v] unless k.nil?}.reject { |a| a.blank? }.flatten.to_json
    render 'country'
 end


def set_user
  @user = User.find(params[:id])
end


# Never trust parameters from the scary internet, only allow the white list through.
def user_params
  params.require(:user).permit(:experience,
                               :kind,
                               :selected_country,
                             ])
end

和user.rb

  attr_accessor :selected_country

当我提交一个国家的表格时,我得到了......

  Couldn't find User with 'id'=American Samoa

我很难理解为什么之前的操作没有正确设置suer并且默认(似乎)选择框中的值

对此有任何建议......

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您使用find属性尝试User selected_country

@country = User.find(params[:user][:selected_country])

因为您将其设置为纯字符串,它会尝试使用您选择的国家/地区查找User

如果您想使用字符串查找值,最好使用find_by方法:

@country = User.find_by country: params[:user][:selected_country]

-

说实话,你的整个nation方法非常糟糕(多个重度数据库调用等)。我会做以下事情:

 def nation
    @country = User.find_by country_params[:selected_country]
    @user_country_array = User.select(:country).distinct
    @user_count = User.where(user_complete: true).count
    @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.to_s.downcase]}.map {|c, v | ["code" => c, "value" => v, "flag" => c.to_s.downcase]}.flatten.to_json #-> this needs to improve
    @sectiona =  User.all.group('practice').count.map { |k,v| [ "name" => k, "y" => v] unless k.nil?}.reject { |a| a.blank? }.flatten.to_json #-> this also needs to improve
    render :country
 end

 private

 def country_params
    params.require(:user).permit(:selected_country)
 end