2013-04-07 44 views
0

我做了railstutorial.org網站上自己的應用程序築底,而現在我對chapter 11幾個問題。一切都很好,我從這個教程學到了很多東西,現在我正在繼續研究我的應用程序,並且我實際上在模型「藝術家」中,每個用戶都可以創建新藝術家ex.Michael Hartl;)並添加他們最受歡迎的報價。問題是允許用戶關注他們最喜愛的藝術家,並看到Feed中的報價,就像來自railstutorial的Microposts一樣。藝術家和用戶是兩種不同的模型,而railstudio不會解釋如何爲此製作「追隨系統」。這就像在YouTube上訂閱頻道等。 有人可以解釋我如何得到這個工作?我必須在代碼中更改什麼?以下藝術家能夠通過用戶 -

按鈕:

<%= form_for(current_user.userartists.build(followed_id: @artist.id)) do |f| %> 
    <div><%= f.hidden_field :followed_id %></div> 
    <%= f.submit "Follow", class: "btn btn-large btn-primary" %> 
<% end %> 

控制器

class UserartistsController < ApplicationController 
def create 
@artist = Artist.find(params[:userartist][:followed_id]) 
current_user.follow!(@artist) 
respond_to do |format| 
format.html { redirect_to @artist } 
format.js 
end 
end 
end 

回答

0

您應該建立一個藝術家模型,並呼籲UserArtist一箇中間模型(或UserFollowsArtist)您將存儲用戶和藝術家之間的所有匹配。現在

class User < ActiveRecord::Base 
    has_many :user_artists 
    has_many :artists, :through => :user_artists 
end 

class Artist < ActiveRecord::Base 
    has_many :user_artists 
    has_many :users, :through => :user_artists 
end 

class UserArtist < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :artist 
end 

你可以叫@user = User.first拿到第一個用戶,並@user.artists得到@user是繼藝術家的名單。

您將不得不創建一個名爲UserArtistsController的單獨控制器,您將在其中執行操作create和可能的destroy(如果用戶希望取消關注該藝術家)。

在你routes.rb

resources :user_artists, :only => [:create, :destroy]

我猜follow button將是Artists顯示頁面,所以你應該有這樣的事情在你看來:

<%= button_to "Follow artist", {:controller => :user_artists, 
     :action => 'create', :artist_id => params[:id] }, :method => :post %> 

而在你的控制器:

class UserArtistsController < ActionController 
def create 
    @user_artist = UserArtist.create(:user_id => current_user.id, :artist_id => params[:artist_id]) 
    @artist = Artist.find(params[:artist_id]) 
    if @user_artist.save 
     redirect_to @artist 
    else 
     flash[:alert] = "Something went wrong, please try again" 
     redirect_to root_path 
    end 
end 

end 

不要忘記爲ArtistUserArtist創建遷移。 UserArtist表應該包含一個user_id和一個artist_id

+0

謝謝你的回答,但這是行不通的。這種方法有幾個問題,並且在整個工作周後,我需要嘗試以其他方式完成此操作。 – eglaza 2013-04-14 14:58:38

+0

什麼是不工作,你有什麼嘗試? – Zippie 2013-04-14 15:00:09

+0

當我點擊藝術家頁面上的「關注」時,它會重新加載站點,並向我顯示按鈕「取消關注」,所以我認爲它現在正在工作。當我通過輸入'@user = User.first'和@ @ user.artists'來查看數據庫(rails c)時,它只顯示''=> []「'。 我想了很多關於這個,我真的不知道爲什麼它不適合我。 – eglaza 2013-04-14 15:10:26