无法将 nil 转换为确切的数字
Posted
技术标签:
【中文标题】无法将 nil 转换为确切的数字【英文标题】:can't convert nil into an exact number 【发布时间】:2013-01-15 14:00:26 【问题描述】:我希望用户能够评论其他人的微博,但我不断收到以下错误:
它来自下面 View/cmets/_form 文件中的时间戳。出于某种原因,@comment.created_at 返回为 nil
View/cmets/_form:(这个partial在每条微博结束时调用)
<span class="content"><%= @comment.content %></span>
<span class="timestamp">Said <%= time_ago_in_words(@comment.created_at) %> ago.</span
<%= form_for(@comment) do |f| %>
<%= f.text_field :content, placeholder: "Say Something..." if signed_in? %>
<% end %>
用户模型:
attr_accessible :name, :email, :password, :password_confirmation #is this secure with password there?
attr_protected :admin #attr_protected necessary?
has_many :microposts, dependent: :destroy
has_many :comments, :through => :microposts, dependent: :destroy
微博模型:
attr_accessible :comment #basically the content of the post
attr_protected :user_id
has_many :comments, dependent: :destroy
评论模型:
attr_accessible :content, :micropost
belongs_to :user
belongs_to :micropost
validates :user_id, presence: true
validates :micropost_id, presence: true
validates :content, presence: true
default_scope order: 'comments.created_at ASC' #is this necessary?
评论控制器:
def create
@micropost = Micropost.find_by_id(params[:id]) #is this necessary?
@comment = current_user.comments.create(:micropost => @micropost)
redirect_to :back
end
用户控制器:
def show
@user = User.find_by_id(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
@micropost = current_user.microposts.build
@comments = @micropost.comments
@comment = current_user.comments.create(:micropost => @micropost) #build, new or create??
end
路线:
resources :users
resources :microposts, only: [:create, :destroy]
resources :comments, only: [:create, :destroy]
SQL:
“评论”=>“内容”=>“示例” 用户负载 (0.8ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'H09yZpAv5qhmT3ok5fXfnQ' LIMIT 1 Micropost Load (0.7ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."id" IS NULL
【问题讨论】:
【参考方案1】:@comment
很可能是一条将created_at
设置为nil
的新记录
【讨论】:
【参考方案2】:@micropost 尚未创建
在@micropost = current_user.microposts.build
之后添加@micropost.save
@micropost = current_user.microposts.build
@micropost.save
@comments = @micropost.comments
@comment = current_user.comments.create(:micropost => @micropost)
【讨论】:
如果在bluid之后添加save,为什么不直接调用create呢? 这是 SQL 说我想要 null micropost id? "comment"=>"content"=>"EXAMPLE" 用户负载 (0.8ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'H09yZpAv5qhmT3ok5fXfnQ' LIMIT 1 Micropost Load (0.7 ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."id" IS NULL以上是关于无法将 nil 转换为确切的数字的主要内容,如果未能解决你的问题,请参考以下文章
无法使用 NSJSONSerialization 将数字转换为 JSON 值
C#,字符串“Number”转换为数值等于多少?为啥用Convert。ToDouble()无法转换???