如何在模型索引页面上添加创建/编辑模型功能? [英] How can I add create/edit models feature on the model index page?

查看:46
本文介绍了如何在模型索引页面上添加创建/编辑模型功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个非常简单的模型:

Ok, I have a model that is very simple:

ServiceType(id: integer, title: string, duration: integer, created_at: datetime, updated_at: datetime)

因为它是如此简单,所以我应该有一个单独的页面来创建和更新这些类型的记录是荒谬的.我想做的是在索引页面上有一个表单,可以用来创建新记录,如果单击编辑链接,我希望该表单加载该记录,以便该表单可以兼作创建/更新表单

Because its so simple, It's ridiculous that I should have a separate page for creating and updating those types of records. What I would like to do is have a form on my index page which I can use to create new records and if I click the edit link, I would like the form to load that record so that the form doubles as a create/update form.

是否有人以前曾经做过此事,或者有人知道某个地方的博客文章显示了如何进行此事?

Has anyone already done this before or does anyone know of a blog article somewhere that shows how to do this?

现在,我使用Laheab在下面发布的博客链接: 如果您使用的是Rails 3,Laheab的链接就是您想要的,但是请注意!编写该代码的人在他的代码中留下了很多明显的错误..寻找诸如*/ */而不是/* */的错误注释块,并寻找他使用jQuery但忽略了$的时间.

Using the blog link posted below by Laheab I am at this point: If you are using Rails 3, Laheab's link is what you want, but BE WARNED!! The guy who wrote it left a ton of obvious errors in his code.. look for bad comment blocks like */ */ instead of /* */ and look for times where he is using jQuery but leaves off the $.

如果您使用的是Rails 2.3.x,我已经发布了对此的修改版本作为答案.

IF you are using Rails 2.3.x, I have posted my modified version of this as an answer.

推荐答案

如果您正在运行Rails 2.3.x,则需要修改该家伙在此

If you are running Rails 2.3.x, you need to modify what the guy does in this blog link.

这是我为获得create/edit/destroy而所做的工作(此方法尚无法使用,由于某种原因,它仍将destroy.js.erb呈现为html):

This is what I did to get create/edit/destroy(this isn't working yet, it still renders destroy.js.erb as html for some reason) it to work:

制作Rails应用程序:

make rails app:

$ rails post_app
$ cd post_app
$ script/generate scaffold Post title:string content:text
$ rake db:migrate

现在添加/替换以下文件:

And now add/replace the following files:

public/javascripts/application.js(请参见Railscasts第136集 http://railscasts.com/episodes /136-jquery ):

public/javascripts/application.js (see Railscasts episode 136 http://railscasts.com/episodes/136-jquery):

// Setting up ajax for sending javascript requests
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  });
  return this;
};

jQuery.fn.getWithAjax = function() {
  this.click(function() {
    $.get(this.href, null, null, "script");
    return false;
  });
  return this;
};

jQuery.fn.postWithAjax = function() {
  this.click(function() {
    $.post(this.href, null, null, "script");
    return false;
  });
  return this;
};

app/controllers/posts_controller:

app/controllers/posts_controller:

class PostsController < ApplicationController
  before_filter :load

  def load
    @posts = Post.all
    @post = Post.new
  end

  def index
  end

  def edit
    @post = Post.find(params[:id])
    respond_to do |format|
      format.all {render :file => "#{RAILS_ROOT}/public/404.html", :status => '404 Not Found'}
      format.js {render :layout => false}
    end
  end

  def create
    @post = Post.new(params[:post])

    if @post.save
      flash[:notice] = 'Post was successfully created.'
      @posts = Post.all
    end

    respond_to do |format|
      format.js {render :layout => false }
    end
  end

  def update
    @post = Post.find(params[:id])

    if @post.update_attributes(params[:post])
      flash[:notice] = 'Post was successfully updated.'
      @posts = Post.all
    end
    respond_to do |format|
      format.js {render :layout => false }
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    flash[:notice] = "Successfully destroyed post."
    @posts = Post.all
    respond_to do |format|
      format.js {render :layout => false }
    end
  end
end

app/views/layouts/posts.html.erb

app/views/layouts/posts.html.erb

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Posts: <%= controller.action_name %></title>
  <%= stylesheet_link_tag 'scaffold' %>
  <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', 'application' %>
  <%= javascript_include_tag 'rails' %>
  <%= yield :head %>
</head>
<body>
  <div id="container">
    <div id="flash_notice" style="display: none; color: green"></div>
    <%= yield %>
  </div>
</body>
</html>

在应用程序/视图/帖子下的

删除所有内容并添加以下文件:

under app/views/posts delete EVERYTHING and add the following files:

index.html.erb:

index.html.erb:

<%- content_for :head do -%>
  <%= javascript_include_tag '/posts.js' %>
<% end %>
<h1>Listing posts</h1>
<%= render :partial => "form" %>
<div id="posts_list">
<%= render :partial => "posts" %>
</div>

index.js.erb:

index.js.erb:

// Setting up the ajax requests for the forms/links.
$(document).ready(function() {
  $("#new_post").submitWithAjax();
  $("a.edit").each(function(){
    $(this).getWithAjax();
  });
  $("a.destroy").each(function(){
    $(this).postWithAjax();
  });
});

create.js.erb:

create.js.erb:

<% if @post.errors.any? -%>
  /*Hide the flash notice div*/
  $("#flash_notice").hide(300);

  /*Update the html of the div post_errors with the new one*/
  $("#post_errors").html("<%= escape_javascript(error_messages_for(@post))%>");

  /*Show the div post_errors*/
  $("#post_errors").show(300);
<% else -%>
  /*Hide the div post_errors*/
  $("#post_errors").hide(300);

  /*Update the html of the div flash_notice with the new one*/
  $("#flash_notice").html("<%= escape_javascript(flash[:notice])%>");

  /*Show the flash_notice div*/
  $("#flash_notice").show(300);

  /*Clear the entire form*/
  $(":input:not(input[type=submit])").val("");

  /*Replace the html of the div post_lists with the updated new one*/
  $("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");
<% end -%>

destroy.js.erb:

destroy.js.erb:

$("#post_errors").hide(300);
$("#flash_notice").html("<%= escape_javascript(flash[:notice])%>");
$("#flash_notice").show(300);
$("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");

_posts.erb:

_posts.erb:

<table>
  <tr>
    <th>Title</th>
    <th>Content</th>
  </tr>
  <% for post in @posts %>
    <tr>
      <td><%= post.title %></td>
      <td><%= post.content %></td>
      <td><%= link_to "Edit", edit_post_path(post), :class => "edit" %></td>
      <td><%= link_to "Destroy", post, :confirm => 'Are you sure?', :method => :delete, :class => 'destroy' %></td>
    </tr>
  <% end %>
</table>

edit.js.erb:

edit.js.erb:

$("#new_post").html("<%= escape_javascript(render(:partial => "form"))%>");
$("#post_title").val('<%= escape_javascript(@post.title)%>');
$("#post_content").val('<%= escape_javascript(@post.content)%>');

_form.erb:

_form.erb:

<% form_for @post do |f| %>
  <div id="post_errors" style="display:none"></div>
  <p>
    <%= f.label :title %><br/>
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :content %><br/>
    <%= f.text_area :content, :rows => 5 %>
  </p>
  <p><%= f.submit %></p>
<% end %>

update.js.erb:

update.js.erb:

<% if @post.errors.any? -%>
  $("#flash_notice").hide(300);
  $("#post_errors").html("<%= escape_javascript(error_messages_for(@post))%>");
  $("#post_errors").show(300);
<% else -%>
  $("#post_errors").hide(300);
  $("#flash_notice").html("<%= escape_javascript(flash[:notice])%>");
  $("#flash_notice").show(300);
  $(":input:not(input[type=submit])").val("");
  $("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");
<% end -%>

这篇关于如何在模型索引页面上添加创建/编辑模型功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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