如何重构此代码,以便在使用相同的基本格式时不会一遍又一遍地重复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
更新:我稍微修改了原来的答案,这对我有用。这是我的修改:
# 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
答案 0 :(得分:3)
将该巨大哈希中的数据设为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
答案 1 :(得分:0)
您可以在Profile类上创建一个返回相同哈希的as_json
方法,然后只执行render :json => profile
。另一种方法是插入ActiveModel::Serializers并告诉它要序列化的属性和方式。