在我的帖子视图中,我有_form
title
和releaseDate
参数。
在我的控制器中,我从params[:post][:title]
获得了值,但params[:post][:releaseDate]
为空。
发布_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 %>
posts_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])
,因为我想对控制器中的title
和releaseDate
执行某些操作。)
post.rb(型号)
class Post < ActiveRecord::Base
attr_accessible :releaseDate, :title, :user_id
belongs_to :user
end
关于如何从表单和控制器中获取日期时间值的任何建议?
答案 0 :(得分: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
并在视图中将所有releaseDate
替换为release_date