Ruby on rails将窗体绑定到对象



在本指南中:

http://guides.rubyonrails.org/v2.3.11/form_helpers.html#binding-a表单到对象

2.2 Binding a Form to an Object部分中,我看到:

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

我得到这样的表格:

<form action="/articles/create" method="post" class="nifty_form">
  <input id="article_title" name="article[title]" size="30" type="text" />
  <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
  <input name="commit" type="submit" value="Create" />
</form>

所以控制器方法create应该被执行,@action应该从表单序列化到它。所以我需要用一些参数来声明create,比如:

def create(action)
action.save!
end

或者,我将如何获取从控制器方法create 中的表单发送的动作对象

所有表单值都作为哈希值传递给该方法。title字段作为params[:article][:title]传递,body作为params[:article][:body]传递,等等

因此,在您的控制器中,您需要根据这些参数创建一个新的Article。请注意,您没有将参数传递给create方法:

def create
  @article = Article.new(params[:article])
  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

这里,@article是Article模型的对象。

<form action="/articles/create" method="post" class="nifty_form">

这个表单的动作是"/articles/create",也就是说,在提交表单时,所有的表单数据都将被发布以创建文章控制器的动作。在那里,您可以通过params获取表单数据。

所以在你的创造行动

def create
    # it will create an object of Article and initializes the attribute for that object
  @article = Article.new(params[:article]) # params[:article] => {:title => 'your-title-on-form', :body => 'your body entered in your form'}
  if @article.save # if your article is being created
    # your code goes here 
  else
    # you can handle the error over here
  end
end

要让create方法保存您的对象,您只需要将参数传递给新对象,然后将其保存为

def create
 Article.new(params[:article]).save
end

在现实中,重定向responsd_to块等方法可能会更困难…

可以通过params实现。

def create
  @article = Article.new(params[:article])
  @article.save!  
  redirect_to :action => :index #or where ever 
rescue ActiveRecord::RecordInvalid => e
  flash[:error] = e.message
  render :action => :new
end

最新更新