我如何重构这段代码,这样我就不会在使用相同的基本格式时一遍又一遍地重复json对象?我对Ruby on Rails还是有点不舒服,所以我不确定最好的方法是什么。
# PUT /users/:user_id/profile/:id
def update
if request.xhr?
profile = current_user.profile
if params[:profile].blank?
render :json => { :error => "There was no profile data passed in so your profile could not be saved." },
:status => :unprocessable_entity
else
if profile.update_attributes(params[:profile])
render :json => { :interests =>
simple_format(h(profile.interests), :class => "pbs tl"),
:favorite_music =>
simple_format(h(profile.favorite_music), :class => "pbs tl"),
:favorite_movies =>
simple_format(h(profile.favorite_movies), :class => "pbs tl"),
:favorite_books =>
simple_format(h(profile.favorite_books), :class => "pbs tl"),
:favorite_foods =>
simple_format(h(profile.favorite_foods), :class => "pbs tl") },
:status => :ok
else
render :json => { :error => get_errors_for_class(profile).to_sentence },
:status => :unprocessable_entity
end
end
end
end
Update:我稍微修改了原始答案,它适用于我。下面是我的修改:
# within profile.rb
# create a hash of profile attributes
def html_to_hash
%w{interests favorite_music favorite_books favorite_foods}.inject({}) do |hash, property|
hash[property] = simple_format(h(self.send(property)), :class => 'pbs tl')
hash
end
end
将这个庞大哈希中的数据设为Profile
的方法
class Profile
def to_hash
[:interests, :favorite_music, :favorite_books, :favorite_foods].inject({}) do |h, prop|
h[prop] = simple_format(h(self.send(:prop)), :class => 'pbs tl')
h
end
end
end
然后# PUT /users/:user_id/profile/:id
def update
if request.xhr?
profile = current_user.profile
if params[:profile].blank?
render :json => { :error => "There was no profile data passed in so your profile could not be saved." },
:status => :unprocessable_entity
else
if profile.update_attributes(params[:profile])
render :json => profile.to_hash,
:status => :ok
else
render :json => { :error => get_errors_for_class(profile).to_sentence },
:status => :unprocessable_entity
end
end
end
end
你可以在你的Profile类上创建一个as_json
方法,它返回相同的哈希值,然后只做render :json => profile
。另一种替代方法是插入ActiveModel::Serializers并告诉它您想要序列化哪些属性以及如何序列化。