在轨道上的红宝石json格式?

时间:2012-07-05 08:17:45

标签: ruby-on-rails-3

如何在数据库中发送数据并在rails3上的ruby中使用json格式显示所需部分?

我的表格就像这样

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :login %><br />
    <%= f.text_field :login %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:1)

在控制器中:

def show
  @user = User.find(params[:user_id]
  respond_to do |format|
    format.json { :render => @user }
  end
end

您可以通过覆盖用户模型中的as_json来自定义JSON输出:

  def as_json(options=false)
    self.include_root_in_json = false
    options = (options || {}).reverse_merge(
      :except => [:updated_at, :created_at, :id],
      :include => :some_association
    )
    super(options)
  end