【问题标题】:Giving the Users the option of either selecting from a dropdown menu or inputting their own and adding it to the table为用户提供从下拉菜单中选择或输入自己的选项并将其添加到表中的选项
【发布时间】:2017-05-02 04:27:49
【问题描述】:

对于新手的问题,我深表歉意。但是,我一直在尝试创建一种特殊类型的关联,但我所有的努力都失败了。我想让用户能够选择他们的家乡城市。我已经列出了一些他们可以选择的选项,但如果它当前不在列表中 - 我希望用户能够简单地添加它“看不到你的城市,添加它”。然后另一个稍后注册的用户可以在他的列表中看到新城市。我已经在下面列出了到目前为止有效的所有相关代码。

非常感谢

家乡城市迁移

class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown

      t.timestamps
    end
  end
end

HomeCity 对用户的参考

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecity, foreign_key: true
  end
end

用户.rb

class User < ApplicationRecord
  cattr_accessor :current_user
  belongs_to :homecity, optional: true
end

Homecity.rb

class Homecity < ApplicationRecord
  has_many :users
end

Edit.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
  <%= f.label :homecity %>
  <br>
  <%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>
</div>
<div class="form-group">
  <%= f.submit "Update", class: 'btn btn-lg btn-block btn-primary' %>
</div>
<% end %>             

Seeds.rb

Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")

Homecities_controller.rb(根据答案创建新的控制器文件)

class HomecitiesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def new
 @homecity = Homecity.new
end
def create
 @homecity = Homecity.new(homecity_params)
end
private
def homecity_params
 params.require(:homecity).permit(:user_id)
end
end

示例类似于 Facebook 在教育方面的做法

【问题讨论】:

  • 只是为了确定:使用州/市图书馆不是更干吗?您仍然可以只显示已分配的城市,但是当他们想要添加新城市时,他们可以从列表中选择它。通过这种方式,您不必审核提交的城市(重复和拼写错误)。
  • @SebastianPlasschaert 非常感谢您的评论。我没有考虑重复和拼写错误的问题。这非常有帮助。但是我想尝试这个的原因是我可以学习如何允许用户从我创建的基本起点向数据库中插入新的东西。

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5


【解决方案1】:

您正在重新发明轮子 - 我猜如果您只是为了学习目的而这样做,那很好,但如果这是一个真正的应用程序,您很可能最好使用 3rd 方 gem。

这个源数据可以很容易地保持最新(参见自述文件)

https://github.com/loureirorg/city-state

如果您不想使用此功能,请向您的页面“添加城市”添加一个按钮,然后通过提交按钮提供一个输入字段,然后将新城市插入您的数据库中。

【讨论】:

  • 非常感谢您的帮助,因为我以前从未做过这样的事情,但我想尝试一下,这样我就可以学习如何将新内容插入数据库。有什么办法可以写下基本的代码示例。
  • 您需要一个带有输入字段、提交按钮并调用控制器方法“create”的表单——我建议您做一些简单的 Rails 教程,对不起,我没有时间为您编写代码。
  • 这太酷了@rmscharry - 所以只是为了确保控制器方法“create”在家庭城市的控制器上虽然正确?
  • 是的,'new' 方法将呈现'new' 表单。
  • 感谢您的指点。我已经用 new 和 create 方法更新了我的控制器。我相信剩下的唯一事情就是改变 html 视图。我需要在 collection_select 中做某件事吗? :
【解决方案2】:

经过几个小时的搜索和关闭后,我想通了。我在下面列出了我所做的事情,以防其他人在类似问题上需要帮助。

  1. 解决此问题的最佳方法是使用 Selectize.js (Rubygems.org)
  2. 将 gem 添加到您的 Gemfile - 运行 bundle install
  3. 确保在 application.scss 中添加 (*= require selectize, *= require selectize.default) 并在 application.js 中添加 (//= require selectize)
  4. 您需要在 Edit.html.erb 中创建一个用于 Homecities 的控制器、一个 edit.js 文件(自定义 selectize、您的数据库和下拉菜单)和一个引导模式

Homecities_controller.rb

class HomecitiesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def create
@homecity = Homecity.new(homecity_params)
if @homecity.save
  render json: @homecity
else
  render json: {errors: @homecity.errors.full_messages}
end
end
private
def homecity_params
params.require(:homecity).permit(:Hometown)
end
end

Edit.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
                  <%= devise_error_messages! %>       
                            <div class="field">
                            <%= f.label :homecity, "Home Town" %><br>
                            <%= f.select :homecity_id, Homecity.all.pluck(:Hometown, :id), {}, { class: "selectize" } %>

                          </div>
                        <div class="form-group">
                    <%= f.submit "Update", class: 'btn btn-lg btn-block btn-primary' %>
                  </div>
            <% end %>

            <div class="modal fade homecity-modal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
              <div class="modal-dialog modal-sm" >
                <div class="modal-content">
                  <div class="modal-header">      
                    <h4 class="modal-title" id="mySmallModalLabel">Create a New City</h4>
                  </div>
                  <div class="modal-body">
                    <%= form_for Homecity.new do |f| %>
                      <div class="form-group">
                        <%= f.label :Hometown %>
                        <%= f.text_field :Hometown, class: "form-control" %>
                      </div>                
                      <div class="form-group">
                        <%= f.submit class: "btn btn-primary" %>
                      </div>
                      <div class="modal-footer">                      
                      <span class="form-control-static pull-right">     
                        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                      </span>
                      </div>
                    <% end %>
                  </div>
                </div>
              </div>
            </div>

Edit.js

$(document).on("turbolinks:load", function() {
var selectizeCallback = null;
$(".homecity-modal").on("hide.bs.modal", function(e) {
if (selectizeCallback != null) {
  selectizeCallback();
  selecitzeCallback = null;
}

$("#new_homecity").trigger("reset");
$.rails.enableFormElements($("#new_homecity"));
});
$("#new_homecity").on("submit", function(e) {
e.preventDefault();
$.ajax({
  method: "POST",
  url: $(this).attr("action"),
  data: $(this).serialize(),
  success: function(response) {
    selectizeCallback({value: response.id, text: response.Hometown});
    selectizeCallback = null;

    $(".homecity-modal").modal('toggle');
  }
});
});
$(".selectize").selectize({
create: function(input, callback) {
  selectizeCallback = callback;

  $(".homecity-modal").modal();
  $("#homecity_Hometown").val(input);
}
});
});

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2015-09-26
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多