Adam
Adam

Reputation: 2997

calling a method on a param before I create a record in rails/ruby

In the create method of my link controller I call the following to make a new link then call a method on the url attribute to remove something:

@link = Link.new(params[:link])
@link.url = strip_http(@link.url)

Is there a way to combine these two statements so i can call the strip_http method on the url param before/as I send it to the database? Feels more efficient and I could reduce my database calls by one.

Upvotes: 0

Views: 51

Answers (1)

Raindal
Raindal

Reputation: 3237

Actually there won't be any database call while you're not calling save or createon your object. But you could do something like this:

params[:link][:url] = strip_http(params[:link][:url])
@link = Link.create(params[:link])

A better solution would be

To use a callback on your model:

class Link < Activerecord::Base
  before_save :strip_http

  def strip_http
    ...
  end
end

And then in your controller action:

@link = Link.create(params[:link])

Nothing else to do in that case. : )

Upvotes: 3

Related Questions