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

가 나는 PinArticle 중첩해야 믿습니다

는 관계입니다. 이 같은 내 route.rb보기 : article#index에서

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

나는 관계를 만들거나 파괴 형태가 : 여기

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

한주의해야 할 점은 자바 스크립트를 사용하지 않으면, 그들은 다시 아니라 POST보다 GET을 사용하는 떨어질 것/삭제한다는 것입니다. 자세한 내용은 documentation을 참조하십시오.