Luc*_*rna 7 ruby-on-rails associations
我对rails非常陌生,我在理解关联方面遇到了一些麻烦.我想建立一个快速的论坛(只是线程 - 发布机制没有别的).我的模型由以下生成:
1. rails generate scaffold Forumthread title:string
2. rails generate scaffold Forumpost title:string content:text username:string
Run Code Online (Sandbox Code Playgroud)
在我的模型中,我添加了协会,即:
class Forumthread < ActiveRecord::Base
has_many :forumposts, dependent: :destroy
end
class Forumpost < ActiveRecord::Base
belongs_to :forumthread
end
Run Code Online (Sandbox Code Playgroud)
在一个线程的显示页面上,我希望能够为该线程进行forumpost.我试图这样做:view:<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
和控制器:
def show
@current_thread = Forumthread.find_by_id(params[:id])
@post = @current_thread.forumposts.build
end
Run Code Online (Sandbox Code Playgroud)
我没有进入创建部分,因为它似乎只是键入@current_thread.forumposts.build来创建一个对象.我错过了什么?我希望@post成为forumpost类型的对象,所以我可以创建@current_thread.forumposts.create(forumposts_params);
目前我收到以下错误:
undefined method `val' for #<Arel::Nodes::BindParam:0x007fe5c0648770>
Run Code Online (Sandbox Code Playgroud)
如果有要求,我会很乐意提供更多数据!.
bas*_*iam 19
我记得读过这个错误时发生的错误foreign_key(https://github.com/rails/rails/commit/78bd18a90992e3da767cfe492f1bc5d63077da8a),看起来这可能是你的情况,因为你在为Forumpost创建脚手架时没有包含它.forumthread_idForumposts的数据库表中是否有列?如果您不知道我在说什么 - 转到db/schema.rb文件,并检查是否可以看到如下内容:
create_table "forumsposts", force: true do |t|
#some other fields
t.integer "forumthread_id", null: false
#some other fields
end
Run Code Online (Sandbox Code Playgroud)
如果没有,您将不得不生成并再运行一次迁移,将此缺失添加foreign_key到Forumspost.在http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-foreign-key :) 上阅读,运行rails generate migration 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4710 次 |
| 最近记录: |