0

我是 ruby​​ 新手,试图遵循官方文档并创建用于创建帖子的基本表单:

<%= form_for @post, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :entry, :size => "60x12" %>
  <%= f.submit "Create" %>
<% end %>

该表单已成功向数据库中添加了一个条目,但是一个空的,我想我的控制器中一定缺少某些东西?我需要以某种方式传递变量吗?

def create
@post = Main.create
end
4

3 回答 3

1

基本的创建操作可能如下所示。您首先初始化一个新帖子。取决于它是否成功保存您继续。

# app/controllers/posts_controller.rb
class PostsController < ActionController::Base
  def create
    @post = Post.new(params[:post])

    if @post.save
      redirect_to @post, notice: 'Post has been created.'
    else
      render :new
    end
  end
end

您可以缩短表格。

<%= form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.text_area :entry, :size => "60x12" %>

  <%= f.submit %>
<% end %>

当你生成一个脚手架时,你可以看到这些优秀的示例代码,所以我鼓励你尝试$ rails generate scaffold Post title body:text通过示例来学习。

于 2013-05-31T10:05:00.343 回答
0

提交表单将输入该表单的值(连同一些其他信息)作为称为“params”的哈希传递给控制器​​ - 参数将包含一个标有表单名称的块,在本例中为“post”。

您需要在创建新对象时使用 params 中的 post 块。

def create
  @post = Main.new(params[:post])
  if @post.save
    # handles a successful save
  else
    # handles validation failure
  end
end
于 2013-05-31T10:01:33.093 回答
0

尝试:

@post = Main.new(params[:post])
@post.save
于 2013-05-31T10:04:39.687 回答