【发布时间】:2017-05-20 13:21:35
【问题描述】:
我想创建一个允许“用户”关注其他用户的 Rails 应用程序。对于更复杂的关系,我是半新手,我正在尝试第一次设置 has_many。我希望朋友能够关注其他用户。
这是我的连接表:
class Following < ApplicationRecord
belongs_to :user
belongs_to :follower, class_name: "User"
end
这是我的用户表:
class User < ApplicationRecord
has_many :followings
has_many :followers, through: :followings
end
这是我的架构:
create_table "followings", force: :cascade do |t|
t.integer "user_id"
t.integer "follower_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
我不知道如何设置表单来实际创建关系。在用户视图中,我有这个,但它不起作用。
<%= form_for @following do |f| %>
<%= f.hidden_field :follower_id, :value => @user %>
<%= f.select :user_id, @users.collect { |u| [u.name, u.id] } %>
<%= f.submit %>
<% end %>
正如我所说,我对这种关系很陌生。我需要帮助。我不知道如何通过表格链接记录。
我正在关注本教程:https://teamtreehouse.com/library/what-is-a-hasmany-through-association-in-ruby-on-rails
【问题讨论】:
标签: ruby-on-rails has-many-through