form_for不提交所有字段

时间:2010-12-19 10:34:08

标签: ruby-on-rails parameters save

使用隐藏字段可以解决我的问题......我知道了......

大家好,

我是rails的新手,试图做一些练习。 我正在编写的应用程序正在尝试创建一个新的“帖子”。请参阅下面的视图和控制器。

但它不像我预期的那样工作...... 参数传递给函数“save”,没有“post_at”字段...

我该如何解决? 感谢

INFO:   Parameters: {"authenticity_token"=>"Xc9VuvRL6GsUTaKyyNQxp8ovylEYwOMC+7hMcqdKizg=", "post"=>{"title"=>"First post", "content"=>"Write something"}, "commit"=>"save"}

查看new_post.erb

<div class="post">
  <% form_for @new_post, :url => { :action => "save" } do |f| %>
    <p><%= f.error_messages %></p>
    <br/>
    <table>
      <tr>
        <td>Title</td>
        <td><%= f.text_field :title %></td>
      </tr>
      <tr>
        <td>Post at</td>
        <td><%= @new_post.post_at %></td>
      </tr>
      <tr>
        <td>Message</td>
        <td><%= f.text_area :content, :cols => 100, :rows => 10 %></td>
      </tr>
    </table>
    <br/>
    <%= f.submit 'save'%>
  <% end %>
</div>

发布控制器

class PostController < ApplicationController
  def index
    @all_posts = Post.find(:all)

    render :action => "post"
  end

  def new
    @new_post = Post.new
    @new_post.post_at = Time.now

    render :action => "new_post"
  end

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

    redirect_to "/post"
  end
end

数据模型:

class Post
  include DataMapper::Resource
  storage_names[:default] = "Post"

  property :id,      Serial
  timestamps :at

  property :title,        String,        :required => true, :length => 500
  property :content,      Text,          :required => true, :lazy => false
  property :post_at,      DateTime
end

3 个答案:

答案 0 :(得分:1)

首先,如果您遵循REST principles

,您的开发会更容易

您的控制器应该代替save实施createupdate方法。


def index
  @posts = Post.all
end

def new
  @post = Post.new
end

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

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

def edit
  @post = Post.get(params[:id])
end

def update
  @post = Post.get(params[:id])
  @post.update_attributes(params[:post])
  redirect_to @post
end

def destroy
  @post = Post.get(params[:id])
  @post.destroy
  redirect_to posts_path
end

这是一个完整的REST控制器,index.html.erb, new.html.erb, edit.html.erb, show.html.erb中的所有视图都有app/views/posts

旁注:如果您是Rails的新手,在尝试使用DataMapper之前,了解如何将其与ActiveRecord一起使用可能是个好主意。这样您就可以使用rails generate scaffold来获得完成所有这些操作的完整示例。

答案 1 :(得分:1)

您的post_at值不是字段,它只显示在表格中。你想这样做:

<tr>
  <td>Post at</td>
  <td><%= f.datetime_select :post_at %></td>
</tr>

但事实上,这个代码的错误多于此。首先,Rails已经有一个字段,它将自动设置为created_at。接下来,您的控制器中的save操作应该是create操作,以遵循Rails约定。

我真的认为你应该阅读涵盖这些基本原理的Getting Started指南,然后更深入地阅读有关Rails的a book or two。这些真的教你很多。

答案 2 :(得分:0)

Ryan对问题的原因是正确的。

如果您需要一个只读字段,那么您可以添加一个隐藏字段以确保该值被回发:

    <td><%= @new_post.post_at %><%= f.hidden_field :post_at %></td>

或者你可以用readonly text_field替换它:

    <td><%= f.text_field :post_at, :readonly => true %></td>
相关问题