使用Rails 3显示同一页面中的所有数据

时间:2015-04-11 04:17:24

标签: ruby-on-rails ruby ruby-on-rails-3

我想在我的表单所在的同一页面中显示数据库中存在的所有数据。我保存了一条记录。请在同一页面提交后帮我显示所有数据。

我的代码如下。

的观点/用户/ index.html.erb

<%= form_for :users,:url => {:action => 'create'} do |f| %>
<p>
    Name: <%= f.text_field :name %>
</p>
<p>
    Email: <%= f.email_field :email %>
</p>
<p>
    content: <%= f.text_field :content %>
</p>
<p>
     <%= f.submit 'Create' %>
</p>
<% end %>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>

  </tbody>
</table>

控制器/ users_controller.rb

class UsersController < ApplicationController
    def index
        @users=User.new
    end
    def create
        @users=User.new(params[:users])
        if @users.save
            flash[:notice]="User has created"
            flash[:color]="valid"
            redirect_to :action => 'index'
        else
            flash[:alert]="User couldnot created"
            flash[:color]="invalid"
            render 'index'
        end
    end
end

我希望在使用Rails 3提交表单后显示在同一个索引页面中。请帮助我。

1 个答案:

答案 0 :(得分:0)

这应该有效

<强>视图/用户/ index.html.erb

<%= form_for :user,:url => {:action => 'create'} do |f| %>
<p>
    Name: <%= f.text_field :name %>
</p>
<p>
    Email: <%= f.email_field :email %>
</p>
<p>
    content: <%= f.text_field :content %>
</p>
<p>
     <%= f.submit 'Create' %>
</p>
<% end %>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody>
    <% @users.each do |u| %>
      <td> <%= u.name%> </td>
      <td> <%= u.email%> </td>
      <td> <%= u.content%> </td>
      <td> <%= link_to 'Show', u %> </td>
      <td> <%= link_to 'Edit', edit_user_path(u) %> </td>
      <td> <%= link_to 'Destroy', u, :method => :delete, :data => { :confirm => 'Are you sure?' } %> </td>
  </tbody>
</table>

<强>控制器/ users_controller.rb

class UsersController < ApplicationController
    def index
        @users=User.all
    end
    def create
        @users=User.new(params[:users])
        if @users.save
            flash[:notice]="User has created"
            flash[:color]="valid"
            redirect_to :action => 'index'
        else
            flash[:alert]="User couldnot created"
            flash[:color]="invalid"
            render 'index'
        end
    end
end