0

How to send data in database and show in needed part by using json format in ruby on rails3?

my form is like this

<%= 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 %>
4

1 回答 1

1

在控制器中:

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

您可以通过覆盖as_jsonUser 模型中的 来自定义 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
于 2012-07-05T14:07:36.077 回答