简体   繁体   中英

Rails: Optional lookup fields

In my Rails app I am using collection_select to provide a list of valid choices for the user. I stored only the id from the looked-up table. I then make a call to the looked-up class in the show view to retrieve the actual value for the id.

in edit:

= f.collection_select :language_id, Language.find(:all, :conditions => ["supported = 't'"]), :id, :language, include_blank: false, :prompt => "Language"

in show:

%p
  %b Language:
  = Language.find(@article.language_id).language_code

This is all working fine unless no choice is made. If the @article.language_id field is null, the view cannot load as the find fails. Any suggestions on how to ignore null values and leave the field blank?

using find_by_id would be an option, as it does not raise an error if the id could not be found.

this issues a call to the database though.

so i would just check the languange_id and provide a default

= @article.language_id.nil? ? default : Language.find_by_id(@article.language_id)

this could also be moved into the model or a helper, so that it does not clutter your view code.

This is a common problem. Simply use try to leave nil values:

 if @article.try(:language_id) != nil
      @code = Language.find(@article.language_id).language_code
    else
      //default nil
      @code = nil
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM