开发者

change params[:link] before @link.save

I want to change a value which I get from an input field before I save it.

pa开发者_如何学Pythonrams[:link]['url'] = "www.facebook.com/redbull"

Now I just want to put "redbull" in the database. The following code fails because it changes the params[:link] before validation. I want to execute it after a valid validation.

def create
    url = params[:link]['url'].split('facebook.com/').last
    params[:link]['url'] = url
    @link = Link.new(params[:link])


    if @link.save
      flash[:success] = 'Link was successfully created.'
      redirect_to root_path
    else
      render 'new'
    end
  end

Thanks in advance

Now it works, thx to caley:

class Link < ActiveRecord::Base

  before_save(:on => :create) do
    self.url = self.url.split('facebook.com/').last 
  end


I'd vote for trying a before_save or after_validation callback in the model to run a custom method you create. You could also add (:on => :create) to the before_save callback so it doesn't run on update.

Something like

class Thing < ActiveRecord::Base
before_save :clean_link

def clean_link
  self.link = self.link.split('facebook.com/').last 
end

Be sure to setup any getters or setters for accessing link if need be. I did something similar in a rails 3 app I've done a bit of work on here


Can you use the "after_validations" callback to do the change? This should be called post validation and before the save is called.

http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M000065


@link = Link.new(:link => url)

or

@link = Link.new
@link.link = url

I am assuming the attribute to which you want save 'redbull' is named link in the above code.


One way is to use delete method of the Hash to remove the key :link and manually set the link attribute.

Like after validation, if the object is valid? you can say params.delete(:link) not before taking it into a variable for ex. @uri = params[:link]['url'].

The code might look like this:

def create
  url = params[:link]['url'].split('facebook.com/').last
  @link = Link.new(params[:link])
  if @link.valid?
    @link.url = url

    @link.save

    flash[:success] = 'Link was successfully created.'
    redirect_to root_path
  else
    render 'new'
  end
end

This method is not tested, but might work.

Update: Like I said, this is one of the ways you can do this. Other way is to employ any of the call back methods like before_save or after_validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜