Home How to properly update active record in ruby
Reply: 1

How to properly update active record in ruby

jose1221
1#
jose1221 Published in 2018-02-02 22:48:51Z

I have model having update method as

def udpate_something(params)
    update(id: params[:id],
           b: params[:b],
           c: params[:c],
           d: params[:d])
end

and in controller

def update
    Model.find(id: params[:id])
         .update_something(id: params[:id]
                           b: params[:b],
                           c: params[:c],
                           d: params[:d])
end

Is this the right way to update or there is a better way?

Tom Lord
2#
Tom Lord Reply to 2018-02-02 23:04:15Z

Firstly, it should be very rare (i.e. virtually unheard of!) to update the id (primary key) of a record. This is a record's identifier; by changing this, you'll mess up any associations and potentially cause a conflict with another record's id.

Also, your udpate_something [SIC] method doesn't really achieve anything. It's a wrapper method that serves no purpose. Why not just do:

def update
  Model.find(id: params[:id])
       .update(b: params[:b],
               c: params[:c],
               d: params[:d])
end

Your controller method doesn't handle error messages, use strong parameters (!!) or perform any render/redirect action - but that's a separate story. There's no generic "right thing to do" across all controller actions; it really depends on what you're trying to achieve!

I'd suggest looking through some basic material such as the rails documentation to see how controllers are typically structured.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.295273 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO