When creating an object in Ruby on Rails, which saving method do you prefer and why?

When writing the "create" method for an object in a Ruby on Rails application, I used two methods. I would like to use one method for cleaner and more consistent code. Two methods are listed below. Does anyone know if anyone else is better? If so, why?

Method 1:

def create1 # is this unsecure? should we grab user_id from the session params[:venue]['user_id'] = params[:user_id] begin venue = Venue.create(params[:venue]) @user_venues = @user.venues render :partial => 'venue_select_box', :success => true, :status => :ok rescue ActiveRecord::RecordInvalid render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity end end 

Method 2:

 def create2 # is this unsecure? should we grab user_id from the session params[:venue]['user_id'] = params[:user_id] venue = Venue.new(params[:venue]) if venue.save @user_venues = @user.venues render :partial => 'venue_select_box', :success => true, :status => :ok else render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity end end 
+7
ruby ruby-on-rails activerecord rescue
source share
4 answers
 class VenuesController < ApplicationController def create @venue = @user.venues.create!(params[:venue]) render :partial => 'venue_select_box', :success => true, :status => :ok end rescue_from ActiveRecord::RecordInvalid do render :text => 'Put errors in here', :success => false, :status => :unprocessable_entity end end 

Using @user.venues in this way, make sure that the user ID is always set accordingly. In addition, ActiveRecord will protect the :user_id field from being assigned during a #create! . Therefore, external attacks cannot change :user_id .

In your tests, you can make sure that executing POST for: create raises an ActiveRecord :: RecordInvalid exception.

+4
source share

I am from the school of thought that exceptions should not be used for ordinary conditions, so I would say that the second is better.

+3
source share

It depends. If you expect all creation statements to work, use the first because the inability to create and save is exceptional and may be a condition from which the program cannot easily recover. Also, if you use relational integrity (foreign_key_migrations from RedHill Consulting), this will throw exceptions due to foreign key violations, so you probably want to catch them when creating or updating.

The second is workable and good, if the request does not succeed, this is what you expect as part of the daily work of this particular action.

In addition, your comment on the code that the session is unsafe - the session is the place to place user_id. As long as you verify that the user is authenticated before doing anything, you will be fine.

+2
source share

I totally agree with don. But I would even take another step with the user_id part and set it as a filter in front of the model.

+1
source share

All Articles