ruby-on-rails – 活动记录关联未定义方法’val'(构建,由has_many创建,belongs_to)

我对rails非常陌生,我在理解关联时遇到了一些麻烦.我想做一个快速的论坛(只是线程 – 发布机制没有别的).我的模型由以下生成
1. rails generate scaffold Forumthread title:string
2. rails generate scaffold Forumpost title:string content:text username:string

在我的模型中,我添加了关联:

class Forumthread < ActiveRecord::Base
    has_many :forumposts,dependent: :destroy
end

class Forumpost < ActiveRecord::Base
    belongs_to :forumthread
end

一个线程的显示页面上,我希望能够为该线程进行forumpost.我想这样做:
视图:
<%= notice%>

<p>
  <strong>Title:</strong>
  <%= @forumthread.title %>
</p>

<% form_for(@post) do |f| %>

<div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="field">
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>


<%= link_to 'Edit',edit_forumthread_path(@forumthread) %> |
<%= link_to 'Back',forumthreads_path %>

和控制器:

def show
    @current_thread = Forumthread.find_by_id(params[:id])
    @post = @current_thread.forumposts.build
  end

我没有进入创建部分,因为它似乎只是输入@ current_thread.forumposts.build来创建一个对象.我错过了什么?
我希望@post成为forumpost类型的对象,所以我可以用@ current_thread.forumposts.create(forumposts_params)创建;

目前我收到以下错误

undefined method `val' for #<Arel::Nodes::BindParam:0x007fe5c0648770>

如果有要求,我会很乐意提供更多数据! .

解决方法

我记得读到当foreign_key丢失时发生的这个错误( https://github.com/rails/rails/commit/78bd18a90992e3da767cfe492f1bc5d63077da8a),看起来这可能是你的情况,因为你在为Forumpost创建脚手架时没有包含它.你在forumposts的数据库表中有forumthread_id列吗?如果您不知道我在说什么 – 转到db / schema.rb文件并检查是否可以看到如下内容
create_table "forumsposts",force: true do |t|
    #some other fields
    t.integer  "forumthread_id",null: false
    #some other fields
 end

如果没有,您将不得不生成并再运行一次迁移,将此缺少的foreign_key添加到Forumspost.在http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-foreign-key :)上阅读它,运行rails生成迁移AddForumthreadIdToForumpost,在新创建的迁移文件中输入类似下面的代码并运行rake db:migrate:

class AddForumthreadIdToForumpost < ActiveRecord::Migration
  def change
    add_column :forumposts,:forumthread_id,:integer,null: false
    add_index :forumposts,:forumthread_id
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...