我有一篇文章與用戶有很多關係,反之亦然。當我創建一篇以用戶身份登錄的文章時,文章就會與用戶建立關係。所以這種關係正在起作用。我希望其他用戶能夠加入本文,所以本質上,我想要一個按鈕將current_user推送到許多用戶的數組/列表。添加/更新用戶文章Rails
我在如何去了解這個過程完全喪失...任何幫助表示讚賞
我有一篇文章與用戶有很多關係,反之亦然。當我創建一篇以用戶身份登錄的文章時,文章就會與用戶建立關係。所以這種關係正在起作用。我希望其他用戶能夠加入本文,所以本質上,我想要一個按鈕將current_user推送到許多用戶的數組/列表。添加/更新用戶文章Rails
我在如何去了解這個過程完全喪失...任何幫助表示讚賞
這樣用戶就可以有很多文章,每篇文章可以屬於多個用戶?聽起來像一個has_and_belongs_to_many
關係。看看相關Rails文檔:
http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
總之你就會有一個articles_users
表,其中每行包括article_id
和user_id
。將新用戶添加到文章時,只需在該表中創建另一條記錄。
或者,如果您認爲您將以該關係作爲單獨實體工作,您可以查看has_many :through
。即文章has_many :users, through: authors
。
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
爲了幫助您決定,該指南提供了一些建議:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :written_articles, class_name: "Article", foreign_key: :user_id
has_and_belongs_to_many :articles
end
#app/models/article.rb
class Article < ActiveRecord::Base
belongs_to :user #-> for the original owner
has_and_belongs_to_many :users
end
上面是has_and_belongs_to_many
協會,它給你的用戶添加到article
的能力:
#config/routes.rb
resources :articles do
match "users/:id", to: :users, via: [:post, :delete] #-> url.com/articles/:article_id/users/:id
end
#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def users
@article = Article.find params[:article_id]
@user = User.find params[:id]
if request.post?
@article.users << @user
elsif request.delete?
@article.users.delete @user
end
#redirect somewhere
end
end
這將允許你使用:
<%= link_to "Add User", article_user_path(@article, @user), method: :post %>
<%= link_to "remove User", article_user_path(@article, @user), method: :delete %>
文章和用戶擁有的has_many:userarticles關係,也是一個的has_many:文章/:用戶,通過:userarticles創建多對多的關係。我相信這是如何做到的,但我也會仔細查看該文檔,謝謝 – PonderingDonkey