2012-08-24 36 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