2014-12-01 128 views
0

所以我有一個具有博客模型和用戶模型的應用程序。has_and_belongs_to_many關聯混淆

現在用戶可以訂閱許多不同的博客,用戶也可以創建他們自己的許多博客。

這個關聯會是什麼樣子?

現在我的模型如下所示:

Blog.rb:

class Blog < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    has_many :posts 

end 

User.rb:

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, 
     :validatable 

    has_and_belongs_to_many :blogs  

    validates :email, uniqueness: true, presence: true 
    validates_presence_of :password, on: :create   

end 

用戶表中有一個blog_id:整型字段,並該博客有一個user_id:整數字段。

這是正確的嗎?

命令如何工作? I.E:

u = User.last 
b = u.blogs.build(title: "bla") 
b.user (shows the owner of the blog) 
b.users (shows the users that have subscribed to the blog) 

最終,我想讓用戶訂閱其他人的博客,並創建自己的博客。

+0

你已經有了Rails 4風格和早期版本的混合。 'validates:password,presence:true,on::create'是可取的。 – tadman 2014-12-01 19:06:24

回答

2

您將要添加第三個模型「訂閱」。然後,您將要使用'has_many_through:'關聯。有關詳細示例,請閱讀導軌指南的這一部分。 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

在創建關聯之後,您將要沿着這些線做些事情: 1)確保將「訂閱」路線正確嵌套在博客路徑下。

resources :blogs, only: [] do 
    resources :subscriptions, only: [:create, :destroy] 

2)創建在app /視圖/訂閱局部一個_subscription.html.erb

3)渲染的部分在博客#表明

<%= render partial: 'subscriptions/_subscription, locals: {blog: @blog} 

4)添加到添加的能力(創建)訂閱中的部分內容:(這只是添加訂閱,您還需要添加刪除功能)

<%= link_to [blog, Subscription.new], class: 'btn btn-primary', method: :post do %> 
    <i class="glyphicon glyphicon-star"> </i>&nbsp; Subscribe 
<% end %> 

5)添加「創建方法」來subscriptions_controller.rb

def create 
    @blog = Blog.find(params[:blog_id]) 
    subscription = current_user.subscriptions.build(blog: @blog) 

    if subscription.save 
     # Add code 
    else 
     # Add code 
    end 
    end 

這應該是足夠的方向,讓你的終點線。祝你好運:)

+0

謝謝!所以我通過創建屬於用戶和博客的訂閱模型來設置HMT關聯。顯然,用戶has_many:訂閱和has_many:博客,通過:訂閱和博客的相同流程。我如何真正允許用戶訂閱博客? – 2014-12-01 20:41:03

+0

我更新了我的答案。我沒有詳細介紹..但它應該給你這個想法。 – fresh5447 2014-12-01 20:59:40

+0

好的,謝謝儘可能多的細節,當你有機會的時候會很棒,但是看起來很棒。會給它一個鏡頭,並回來! – 2014-12-01 21:10:04