Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couldn't find ArticlesSkill with ID=1 for Article with ID=

I am trying to create an article.

class Article < ActiveRecord::Base

 belongs_to :article_skill
  attr_accessible :articles_skill_attributes

  accepts_nested_attributes_for :articles_skill 
end

class ArticlesSkill < ActiveRecord::Base
  attr_accessible :description, :name

  has_many :articles

end

This is my form in the article/new.html.erb

 <%= article_form.fields_for :articles_skill, @article.articles_skill do |b|%>
    <label class="medium"><span class="red">*</span> Skill</label>
    <%= b.select :id, options_for_select(ArticlesSkill.all.collect{|m| [m.name, m.id]}) %>  
  <%end%>

Here the article_form is the builder for the @article form object.

If I try to save the @article object its showing this error.

Couldn't find ArticlesSkill with ID=1 for Article with ID=
like image 790
Karthikds Avatar asked Dec 15 '22 11:12

Karthikds


2 Answers

I've been struggling with this problem for a few days. Did a lot of searching.. it took going to the rails console and searching by the exception being thrown instead to make any progress with this.

Check out this answer on this question for why it's happening, and possible workarounds. Use rails nested model to *create* outer object and simultaneously *edit* existing nested object?

Be aware that using the first option presented here creates a security hole as described in http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-3933

like image 77
bdx Avatar answered Jan 23 '23 11:01

bdx


The second parameter in your fields_for call seems unnecessary. ActiveRecord is performing a lookup on the association articles_skill for @article when it reaches that param, but since the @article is new and has yet to be saved, it has no ID and triggers an error.

<%= article_form.fields_for :articles_skill do |b|%>
 <label class="medium"><span class="red">*</span> Skill</label>
 <%= b.select :id, options_for_select(ArticlesSkill.all.collect{|m| [m.name, m.id]}) %>  
<% end %>
like image 27
Lawson Kurtz Avatar answered Jan 23 '23 11:01

Lawson Kurtz