title: Where do I use the find_or_create_by method?
body: <p>When using the Rails method, find_or_create_by, does it belong in the model or the controller? I am having a hard time understanding how to actually implement this method.</p>
  
  <p>I want my rails application to accept JSON messages from users. The users will be sending data back to the server so it can be saved in the database. That being said, I would assume the user would have to use the 'POST' or 'PATCH method to store or update the data on my server. When I look at my routes the 'POST' method is used by the create action.</p>
  
  <p>I have read the following Rails documentation but it didn't clarify anything to me. <a href="http://guides.rubyonrails.org/active_record_querying.html#find-or-create-by" rel="nofollow">http://guides.rubyonrails.org/active_record_querying.html#find-or-create-by</a></p>
  
  <p>Would I place the find_or_create_by method in my create action like so? Or does it belong somewhere else? It doesn't seem right in the create action...</p>
  
  <pre><code>class WifiNetworksController &lt; ApplicationController
    def create
      @wifi_network = WifiNetwork.find_or_create_by(bssid: params[:bssid],
                                          ssid: params[:ssid],
                                          channel: params[:channel], etc...)
    end
  end
  </code></pre>
  
  <p>Ultimately I want:</p>
  
  <ol>
  <li>Users to save new networks via JSON if it doesn't exist</li>
  <li>Users to update existing networks via JSON if certain attributes have improved (like signal strength)</li>
  </ol>
  
  <p>Thank you for your time!</p>
  
  <p>Final Update - Thanks for the great advice everyone! I had to take a bit of everybody's advice to get it to work! Below is what I ended up doing.. Seems to work well with no errors.</p>
  
  <pre><code>def create
    respond_to do |format|
      if @wifi_network = WifiNetwork.find_by(bssid: wifi_network_params[:bssid])
        # Logic for checking whether to update the record or not
        @wifi_network.update_attributes(wifi_network_params) if @wifi_network.rssi &lt; params[:rssi]
        format.json { render :nothing =&gt; true }
      else
        # Must be a new wifi network, create it
        @wifi_network = WifiNetwork.create(wifi_network_params)
        format.json { render :nothing =&gt; true }
      end
    end
  end
  </code></pre>