On May 26, 2014, at 8:38 AM, Ronald Fischer wrote:

> I thought this is an easy one, but: I have created a record, and later
> would like to retrieve it again.
> 
> Here is an excerpt of my schema:
> 
> create_table "dicts", force: true do |t|
>    t.string   "dictname"
>    ...
>  end
> 
> My model ensures that dictname is unique:
> 
>   validates   :dictname,
>               presence: true,
>               length: { minimum: 3 },
>               format: { with: /\A\D/ },
>               uniqueness: true
> 
> In my controller, I tried this to fetch a Dict object, when the value
> for the :dictname field is stored in variable dict_name:
> 
> if Dict.exists?(:dictname => dict_name)
>      logger.debug('found dictionary with name '+dict_name)
>      dictid=Dict.where(:dictname => dict_name).select('id').first.id
>      logger.debug('dictid='+dictid.inspect)
>      @dict=Dict.find(dictid)
> 
> However, the line to calculate dictid fails with
> 
>   TypeError (can't cast Hash to integer)
> 
> which would suggest that the hash argument to the 'where' method is
> unexpected. But this can't really be, can it?
> 
> So, my questions:
> 
> - Why do I get this error?
> 
> - How do I fix it?
> 
> - The whole procedure to get at my Dict record, looks unnecessarily
> convoluted to me. Isn't there an easier way to do it?

ActiveRecord already has a finder that can do all this in one line:

        Dict.first_or_create(url: params[:dictname])

Assuming that's the only thing needed to create or find an existing Dict, you 
should be all good there.

Walter


> 
> -- 
> Posted via http://www.ruby-forum.com/.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to [email protected].
> To post to this group, send email to [email protected].
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/rubyonrails-talk/acd4904d49a136d008319f198800eef1%40ruby-forum.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/23E1DCC4-AD78-4AAE-899C-E24786C32881%40wdstudio.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to