2013-07-08 69 views
0

在本指南:Ruby on Rails的结合形式对象

http://guides.rubyonrails.org/v2.3.11/form_helpers.html#binding-a-form-to-an-object

在部分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应该从表单序列化到它。所以,我需要声明与像一些参数创建:

def create(action) 
action.save! 
end 

要不我怎么会得到操作对象的保持这是我从形式发送的控制方法创建

回答

1

所有形式的值传递给方法作为散列。该title场为params[:article][:title]过去了,body作为params[:article][:body]

所以在你的控制器,你需要创建这些PARAMS新Article。请注意,你不参数传递给create方法:

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

让创建方法保存你的对象,你只需要传递参数给新的对象,比保存

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

现实方法可能会更加困难与重定向respond_to块等...

1

在这里,@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 
0

能做到这一点通过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