alfa alfa - 2 months ago 10
Ruby Question

Delete child table data in ruby on rails

I have three table like,

user
,
article
,
saved_article
,

User

has_many : saved_articles, dependent: :destroy


Article

has_many : saved_articles, dependent: :destroy


SavedArticle

id | article_id | user_id | #-> Table

belongs_to :user
belongs_to :article


SavedArticle
creating success fully but problem is when I try to delete,

My deleting action:

def remove
current_user.saved_articles.find(params[:id]).destroy
redirect_to home_path
end


Remove form:

<%= form_for :remove, url: home_remove_path(id: current_user.saved_articles.id), method: :delete, remote: true do |f| %>
<%= f.button 'Remove'.html_safe, data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Deleting..."}, :class => 'btn btn-default btn-delete' %>
<% end %>


Showing based on upper code :


undefined method `id' for #SavedArticle::ActiveRecord_Associations_CollectionProxy:0x00000016fddd90


When I debug like below:

<%= debug current_user.saved_articles %>
then showing all attribute inside the table.

my question is how can I delete my specific attribute from
saved_articles
table.

Thanks

Answer

I think here is your solution like below:

<% for n in current_user.saved_articles %>
  <% if n.user_id == user.id && n.article_id == article.id %> #-> user_id & article_id is your foreign_key
    <%= form_for :remove, url: home_remove_path(id: n.id), method: :delete, remote: true  do |f| %>
      <%= f.button 'Remove'.html_safe, data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Deleting..."}, :class => 'btn btn-default btn-delete' %>
      <% end %>
  <% end %>
<% end %>

And In your controller add before_action :authenticate_user! This will ensure that in whatever you are doing.

def remove
  SavedArticle.find(params[:id]).destroy
  redirect_to home_path
end

I think that is the ideal way

Comments