0
我想創建一個應用程序,用戶可以關注或取消關注文章。爲此,我創建了三個模型,分別爲Customer
,Article
和Pin
。關注並取消關注文章
這些都是關係:
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
現在我在這裏兩個問題:
- 如何創建一個可以刪除當前關係的表單?
- 在我的表單中,我只想顯示其中一個按鈕。我如何有條件地顯示正確的按鈕?