Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It depends. You are passing a hash of data to the model and saying "make sense of this".</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_params(params) .... end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_params(params) end end </code></pre> <p>This is OK. But you may find yourself wanting to do this from many different actions. You are unlikely to be able to make the params exactly the same in each case, so you will need multiple methods on your model, one for each action:</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_update_params(params) # do stuff end def update_from_settings_params(params) # do different stuff end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_update_params(params) end def change_settings ... @model.update_from_settings_params(params) end end </code></pre> <p>This is not OK and you are making the model do controller work. A reasonable halfway house is to create a method on your model that accepts a canonical data hash, and then translate between the params and the canonical hash in the controller:</p> <pre><code>class Model &lt; ActiveRecord::Base def update_from_data(hash) validate_data!(hash) # do stuff end end class ModelsController &lt; ActionController::Base def update ... @model.update_from_data(translate_update_params) end def change_settings ... @model.update_from_data(translate_change_settings_params) end end </code></pre> <p>Although you should make sure to carefully document the format of the data hash that the model accepts. We actually go so far as to use a YAML validation library (<a href="http://rjbs.manxome.org/rx/" rel="nofollow noreferrer">Rx</a>) to ensure that the model only accepts valid data.</p> <p>Sorry about the long answer, but I haven't got the time to write a shorter one ;).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload