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