1

我正在尝试创建一个用户可以关注或取消关注文章的应用程序。为此,我创建了三个模型CustomerArticlePin

这些是关系:

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

我相信 aPin必须嵌套在 a 中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

现在在这里我的两个问题:

  • 如何创建可以删除当前关系的表单?
  • 在我的表单中,我只想显示其中一个按钮。如何有条件地显示正确的按钮?
4

1 回答 1

1

您不需要表格来删除关系,链接就可以了。我假设您将在索引视图中遍历您的文章——如果是这样,这样的事情怎么样?

<% @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 %>

关于用于创建/销毁记录的一个警告link_to是,如果禁用了 javascript,它们将回退到使用 GET 而不是 POST/DELETE。有关详细信息,请参阅文档

于 2012-08-24T22:05:05.150 回答