Ruby 将post与用户关联
这里是与原始问题相关的三个文件,我想…请原谅我的无知…rails生成器为您做了很多工作,所以我还不了解所有的连接Ruby 将post与用户关联,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,这里是与原始问题相关的三个文件,我想…请原谅我的无知…rails生成器为您做了很多工作,所以我还不了解所有的连接 class Post < ActiveRecord::Base has_many :comments belongs_to :user default_scope { order('created_at DESC') } end 发生错误时: Ruby基本上是告诉您,在第11行,post对象的用户关联为nil,即一个不存在的值,
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
default_scope { order('created_at DESC') }
end
发生错误时:
Ruby基本上是告诉您,在第11行,post对象的用户关联为nil,即一个不存在的值,在Ruby中是类的一个单实例 因此,您试图在nil上调用namemethod,它显然没有这样的方法,因此使用了NoMethodError
只需在打印其名称之前添加一个检查,以确保用户存在,或者确保始终有一个用户与您的帖子关联,例如,通过一个最适合您的场景的用户。@sandipon:谢谢您的清理,但是我在哪里可以找到.name?您收到了错误,因为没有定义post.user。您是否关联了Post和用户模型?你是怎么保住这个职位的?请发布用于保存新帖子的控制器操作。例如,postscreate。
class AddUserToPosts < ActiveRecord::Migration
def change
add_column :posts, :user_id, :integer, :name
add_index :posts, :user_id
end
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body
t.text :name #added this
t.timestamps
end
end
end
<%= link_to post.title, post %>
</h4>
<small>
>> submitted
<%= time_ago_in_words(post.created_at) %> ago by
<%= post.user.name %> <br/>
<!-- <%= post.comments.count %> Comments -->
</small>