你也可以试试这个:
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
一些测试:
require 'ostruct'
@annotation = OpenStruct.new
params = {:annotation => {:note => 'note', :style => 'style'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct note="note", style="style">
@annotation = OpenStruct.new
params = {:annotation => {:note => nil, :style => 'style'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct style="style">
@annotation = OpenStruct.new
params = {:annotation => {:note => 'note'}}
params[:annotation].each_pair {|k,v| v && @annotation.send("#{k}=", v) }
p @annotation
#<OpenStruct note="note">