隐藏的Rails模型中的属性 [英] Hiding Rails Model Attributes

查看:185
本文介绍了隐藏的Rails模型中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的API中的控制器:

I have a controller for an API that looks like this:

def index
  respond_to   do |format|
    format.json  { render :json => @groups.to_json(:only => [:id, :name, :description, :created_at, :updated_at])}
  end
end

def show
  respond_to   do |format|
    format.json  { render :json => @group.to_json(:only => [:id, :name, :description, :created_at, :updated_at]) }
  end
end

# @todo add store to item
def create
  if @group.save
    render :json => @group.to_json(:only => [:id, :name, :description, :created_at, :updated_at])
  else
    render :status => 406
  end
end

def update
  if @group.update_attributes(params[:group])
    render :json => @group.to_json(:only => [:id, :name, :description, :created_at, :updated_at])
  else
    render :status => 406
  end
end

def destroy
  @group.destroy
  render :text => ""
end

正如你所看到的,我重复我自己很多。我很乐意做这些(而且只有这些)的属性可以通过模型的方式,也没有找到一个合适的解决方案。有什么来保护大众写作的属性?或者我可能意味着大众阅读?

As you can see, I'm repeating my self a lot. I'd love to make these (and only these) attributes available by way of the model, but couldn't find a fitting solution. Is there anything to protect attributes from mass writing? Or do I possibly mean mass reading?

正如评论指出下面我想和属性的模式,名称 i_am_private 。当我渲染模型作为JSON - 渲染:JSON => @model - 我只想名称现身

As noted in comments below I want to have a model with attributes, name and i_am_private. When I render that model as json - render :json => @model - I want only name to show up.

红宝石1.8.7
轨道3

Ruby 1.8.7 Rails 3

推荐答案

如何在组模式覆盖as_json方法?

How about overriding as_json method in your Group model?

class Group < ActiveRecord:Base
  ...
  def as_json(options={})
    {
      :id => id,
      :name => name,
      :description => description,
      :created_at => created_at,
      :updated_at => updated_at
    }
  end
end

这篇关于隐藏的Rails模型中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆