Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to check if a record exists before creating a new one in rails3?
    primarykey
    data
    text
    <p>Heres what I'm trying to accomplish: </p> <ul> <li>I have a tagging system in place. </li> <li>Tags are created, when Posts are created (posts has_many :tags, :through => :tag_joins. </li> <li>A tag join is automatically created when a post is created with tags). </li> </ul> <p>I want to check if the tag already exists. If it does I want to use the existing tag for the tag_join record, rather than creating a new tag record.</p> <p>Here is my current code, which isn't working.</p> <pre><code>class Tag &lt; ActiveRecord :: Base belongs_to :user belongs_to :tag_join belongs_to :post before_create :check_exists def check_exists tag = Tag.where(:name =&gt; self.name, :user_id =&gt; current_user.id) if tag.nil? tag = Tag.create(:name =&gt; self.name, :user_id =&gt; current_user.id) end end end </code></pre> <p>This doesn't work though, I'm getting an error upon task creation...(the server is actually just timing out - I don't receive a specific error).</p> <p>Any ideas?</p> <p>Tokland said I was creating an infinite loop by telling it to create tag again - so I tried this:</p> <pre><code> def check_exists tag = Tag.find_by_name_and_user_id(:name =&gt; self.name, :user_id =&gt; current_user.id) if tag != nil self.id = tag.id end end </code></pre> <p>And still get the server timeout</p> <p>Edit: I'm not sure if this matters, but the way the tags are being added is similar to "http://railscasts.com/episodes/73-complex-forms-part-1</p> <p>they're nested in the post form, and use something like this:</p> <pre><code>def tag_attributes=(tag_attributes) tag_attributes.each do |attributes| tags.build(attributes) end end </code></pre> <p>I'm wondering if this is stopping this whole thing from working? Also, using current_user.id in the model definitely seems to be an issue...</p> <p><strong>EDIT:</strong></p> <p>Something I have figured out: this had to change, the format we were using before was incorrect syntax - generally used for a .where method.</p> <pre><code> def check_exists @tag = Tag.find_by_name_and_user_id(self.name, self.user_id) if @tag != nil #return false #self=@tag end end </code></pre> <p>The problem now is this, I can learn if it the tag already exists. But then what? If I go with the return false option, there is an error upon post creation, and the join record isn't created... The other option "self=@tag" obviously just doesn't work.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload