首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Rails中,如何在Haml中使用RESTful控制器?

在Rails中,在Haml中使用RESTful控制器,可以通过以下步骤实现:

  1. 首先,确保已经安装了Haml gem,并在Gemfile中添加了相应的依赖。
  2. 在控制器中,使用RESTful路由来定义相应的操作。例如,在app/controllers/posts_controller.rb文件中:
代码语言:ruby
复制
class PostsController< ApplicationController
  def index
    @posts = Post.all
  end

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

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post
    else
      render 'new'
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :body)
  end
end
  1. 在Haml模板中,使用RESTful路由来生成相应的链接和表单。例如,在app/views/posts/index.html.haml文件中:
代码语言:haml
复制
%h1 All Posts

= link_to 'New Post', new_post_path

- @posts.each do |post|
  %h2= link_to post.title, post_path(post)
  %p= post.body

app/views/posts/new.html.haml文件中:

代码语言:haml
复制
%h1 New Post

= form_with model: @post, local: true do |form|
  = form.label :title
  = form.text_field :title

  = form.label :body
  = form.text_area :body

  = form.submit 'Create'

app/views/posts/show.html.haml文件中:

代码语言:haml
复制
%h1= @post.title
%p= @post.body

= link_to 'Edit', edit_post_path(@post)
= link_to 'Back', posts_path

这样,在Haml中就可以使用RESTful控制器来实现CRUD操作。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券