0

在我的帖子视图中,我有一个_form带有titlereleaseDate参数的。

在我的控制器中,我从 中获取值params[:post][:title],但params[:post][:releaseDate]是空的。

post_form

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :releaseDate %><br />
    <%= f.datetime_select :releaseDate %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

post_controller

def create
    @title = params[:post][:title]
    @date = params[:post][:releaseDate]

    @post = Post.new(title: @title, releaseDate: @date)
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

(我没有使用@post = Post.new(params[:post]),因为我想对控制器中的titleand做一些事情。)releaseDate

post.rb (模型)

class Post < ActiveRecord::Base
  attr_accessible :releaseDate, :title, :user_id
  belongs_to :user
end

关于如何从表单中获取日期时间值并进入我的控制器的任何建议?

4

1 回答 1

0

releaseDate不是 rails 约定,尝试将字段重命名为release_date. 也许这会有所帮助。

为了证明这个概念,您可以使用所谓的虚拟属性:像这样将 release_date getter 和 setter 添加到模型中(请注意,日志可以帮助您缩小问题范围):

class Post < ActiveRecord::Base
  attr_accessible :releaseDate, :title, :user_id
  belongs_to :user

  def release_date
    date = read_attribute('releaseDate')
    logger.debug("READ DATE IS #{date} aND CLASS IS #{date.class}") # see this in rails server logs 
  end

  def release_date=(date)
    logger.debug("WRITE DATE IS #{date} aND CLASS IS #{date.class}") # see this in rails server logs 
    write_attribute('releaseDate', date)
  end
end

并在视图中全部替换releaseDaterelease_date

于 2013-03-26T11:04:35.703 回答