Topic: Passing params from form to Model

I would like to allow input from a form to be passed back to my model in order to be used in a complex db query.

The example I have uses attr_reader and attr_writer but gets a little complicated from there.
I am trying to get my input from my view into the self.db_query in my info model. Here is the code I have and was wondering if there was an easier way or if someone had a working example:

class Info < ActiveRecord::Base
attr_reader :input
attr_writer :input
def initialize(data)
        @input = data

def self.db_query
                :order => "name",
                :conditions => "name = 'INPUT FROM FORM SOMEHOW GOES HERE'"

Any help at all is greatly appreciated! Thanks...

Re: Passing params from form to Model

Why not pass the parameters through the method. For example:

  # find with conditions on params

# controller

Passing the params like this somewhat breaks the MVC principle. It would probably be better to restrict which parameters are passed to the model.

Railscasts - Free Ruby on Rails Screencasts

Re: Passing params from form to Model

I see..thanks for the reply.
I'd rather not break the model if I don't have to.
Is it possible to take in the (params) from my view and only pass them to my that point, use the :conditions=> parameter to the built in find_all to get detailed database queries without having to config anything in the model?

I guess my question is; is it possible to run detailed db queries directly from my controller using something like:

@x=Info.find(:all, :conditions => "field1 = 'DATA-passed from params' and field1 > 'OTHER-passed from params'")

thanks again

Last edited by jackster (2007-01-16 13:56:09)

Re: Passing params from form to Model

Yes.  Actually, that's often the easiest way.  This is an example of code that (if you had the right fields defined) would work:

@infos = Info.find(:all, :conditions => ["name = ? and size = ? and density = ?", params[:name], params[:size], params[:density]])

The syntax of that is a little funny, but that array that's passed to conditions is a slick way to make sure your params values are all properly escaped.  It avoids somebody doing a mysql injection on you.