ruby-on-rails – 活动记录关联未定义方法’val'(构建,由has
我对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.我想这样做: <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来创建一个对象.我错过了什么? 目前我收到以下错误: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |