2012-08-24 38 views
0

我想創建一個應用程序,用戶可以關注或取消關注文章。爲此,我創建了三個模型,分別爲Customer,ArticlePin關注並取消關注文章

這些都是關係:

Customer 
    has_many articles 
    has_many pins 
Article 
    has_many pins 
    belongs_to customer 
Pins 
    belongs_to customer 
    belongs_to article 

我相信Pin必須嵌套的Article內。我route.rb這個樣子的:

resources :articles do 
    resources :pins, :only => [:create, :destroy] 
    end 
end 

article#index我有創建或銷燬的關係的一種形式:

# To create 
<%= form_for [article, current_customer.pins.new] do |f| %> 
    <%= f.submit "Pin" %> 
<% end %> 
# To destroy which doesn't work because i guess you can't do the form like that 
<%= form_for [article, current_customer.pins.destroy] do |f| %> 
    <%= f.submit "Pin" %> 
<% end %> 

這裏有相應的控制措施:

def create 
    @article = Article.find(params[:article_id]) 
    @pin = @article.pins.build(params[:pin]) 
    @pin.customer = current_customer 

    respond_to do |format| 
    if @pin.save 
     format.html { redirect_to @pin, notice: 'Pin created' } 
    else 
     format.html { redirect_to root_url } 
    end 
    end 
end 

def destroy 
    @article = Article.find(params[:article_id]) 
    @pin = @article.pins.find(params[:id]) 
    @pin.destroy 

    respond_to do |format| 
    format.html { redirect_to root_url } 
    end 
end 

現在我在這裏兩個問題:

  • 如何創建一個可以刪除當前關係的表單?
  • 在我的表單中,我只想顯示其中一個按鈕。我如何有條件地顯示正確的按鈕?

回答

1

你不需要一個表單來刪除關係,鏈接將會很好。我假設你會在索引視圖中迭代你的文章 - 如果是的話,那麼這樣的事情呢?有關使用link_to創建/銷燬記錄

<% @articles.each do |article| %> 

    ... 

    <% if (pin = current_customer.pins.find_by_article(article)) %> 
    <%= link_to 'Unfollow', articles_pin_path(article, pin), :confirm => "Are you sure you want to unfollow this article?", :method => :delete %> 
    <% else %> 
    <%= link_to 'Follow', articles_pins_path(article), :method => :post %> 
    <% end %> 
<% end %> 

一個需要注意的是,如果JavaScript被禁用,他們將回落到使用GET而不是POST/DELETE。詳細信息請參見documentation