新手问题 NOmethod Error 新手求助啦。。。。

arc_start · 2015年08月07日 · 最后由 arc_start 回复于 2015年08月07日 · 2851 次阅读

用的是 ubuntu15.x.x rails 是 4.23 问题是 undefined method `chat' for #Chat:0x007fe686475850 Extracted source (around line #29):

def create
  @chat = Chat.create(chat_params)
  if @chat.save
    redirect_to chats_path
  else

#下面是控制器的

def create
  @chat = Chat.create(chat_params)
  if @chat.save
    redirect_to chats_path
  else
    flash.now[:warning] = "error"
    render 'new'
  end
end

#这是视图

<div class:"col-md-4 col-md-offset-4">
<h1>new add comment panel</h1>

<hr>
<%= simple_form_for @chat do |f|%>
<div class="form-chat">
<%= f.input :title, input_html:{ class:"form-control"}%>
<%= f.input :desc, input_html:{ class:"form-control"}%>
</div>
<%= f.submit "submit", data:{disable_with: 'Submitting---'}, class:"btn btn-primary"%>
<%end%>
</div>

明明之前好好的,什么都没改,莫名其妙错了,求大家帮助呢!...

贴 Rails 控制台日志,错误那部分

@huacnlee 已贴,谢谢回复!XD

Started POST "/chats" for 127.0.0.1 at 2015-08-07 11:05:24 +0800
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ChatsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"jBWT5FEJAE6aRBUFtz7DNsVkaP9Bmvhl3B40AnfAKBN/Y/wvNX5ROHADkALzDHaXsohjM+qNAqGy1mEgfo2XJQ==", "chat"=>{"title"=>"fuck day", "desc"=>"恩,哦yeah"}, "commit"=>"submit"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
   (0.0ms)  rollback transaction
Completed 500 Internal Server Error in 34ms (ActiveRecord: 0.9ms)

NoMethodError (undefined method `chat' for #<Chat:0x00000002c81ac0>):
  app/controllers/chats_controller.rb:30:in `create'

app/controllers/chats_controller.rb 30 行是这段么?

@chat = Chat.create(chat_params)

这代码有点怪:

@chat = Chat.create(chat_params) #创建了一个 chat,下面又 save 一次,改成 Chat.new(chat_params)
if @chat.save
......
end

#5 楼 @mouse_lin 。。。可是很多新手教学都是 create 再 save 不是吗...还是同样的错误呢,并没有用..

#6 楼 @arc_start chat_params 的定义错了呗 你应该把 { chat: {} } 直接传给 Chat.create

def chat_params
  params.require(:chat).permit!
end

#7 楼 @zlx_star 。。。原来是这样定义的哈...有错误吗?

private 
    def chat_params
        params.require(:chat).permit(:title, :desc)
    end```

@huacnlee @mouse_lin @zlx_star ,抱歉...不小心在 model 中添加了 validates:chat..把自己给过滤了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号