开发者

Select tag - using logic to specify the selected value

I have a form select where开发者_运维百科 by default, I need a 'main' root folder selected, but I also need it to use params if they exist for the selected option. I've seen examples of using params as the selected unless they're nil. But, I haven't seen an example of using another value if the param is nil (use this unless it's blank, in which case - use this other thing).

VIEW

 <%= f.select :folder_id,  options_for_select(@folders, @folder_to_select )  %>

CONTROLLER:

if  !params[:contact][:folder_id].nil?
   @folder_to_select = params[:contact][:folder_id].to_i
else
   @folder_to_select = @folders.assoc('MAIN').last.to_i
end   

Can I get that controller logic functionality all inside Select?

Thanks!

edit:

I missed it but my originall controller code didn't actually work. I had to check if the [:contact] param was nil before I could check if [:contact][:folder_id] was nil (to avoid a nil error if the top level [:contact] didn't exist.

if !params[:contact].nil?
  if !params[:contact][:folder_id].nil?
     @folder_to_select = params[:card][:folder_id].to_i
  else
     @folder_to_select = @folders.assoc('MAIN').last.to_i
  end
end


Yes.

<%= f.select :folder_id,  options_for_select(@folders, params[:contact][:folder_id].to_i || @folders.assoc('MAIN').last.to_i)  %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜