Jseb
Jseb

Reputation: 1934

Follow and unfollow an article

I am trying to create an app where a user can follow or unfollow an article. To do that, I created three models, Customer, Article and Pin.

These are the relationships:

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

I believe a Pin must be nested within an Article. My route.rb look like this:

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

In article#index I have a form for creating or destroying the relationships:

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

Here are the corresponding controller actions:

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

Now here my two questions:

Upvotes: 1

Views: 227

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

You don't need a form to delete the relationship, links will do fine. I assume you'll be iterating through your articles in the index view -- if so, how about something like this?

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

One caveat about using link_to for creating/destroying records is that if javascript is disabled, they will fall back to using GET rather than POST/DELETE. See the documentation for details.

Upvotes: 1

Related Questions