Ruby on rails 基本RubyonRails未定义方法问题
我是RoR开发的相对业余爱好者(大约有一个月的经验),在这之前,我一直在引用来自不同控制器的变量,没有任何问题。我正在为一个博客开发一个CMS,但我无法将博客作者的用户名显示在索引或显示页面上。我收到一个“nil:NilClass的未定义方法`username'”错误。但是,我可以获得ID。有人能帮我指出代码中的错误吗?我将不胜感激 这是博客模式:Ruby on rails 基本RubyonRails未定义方法问题,ruby-on-rails,ruby,sqlite,rails-activerecord,Ruby On Rails,Ruby,Sqlite,Rails Activerecord,我是RoR开发的相对业余爱好者(大约有一个月的经验),在这之前,我一直在引用来自不同控制器的变量,没有任何问题。我正在为一个博客开发一个CMS,但我无法将博客作者的用户名显示在索引或显示页面上。我收到一个“nil:NilClass的未定义方法`username'”错误。但是,我可以获得ID。有人能帮我指出代码中的错误吗?我将不胜感激 这是博客模式: class Blog < ActiveRecord::Base attr_accessible :post, :title
class Blog < ActiveRecord::Base
attr_accessible :post, :title
has_one :users
belongs_to :user
end
以下是index.html.erb代码:
<% @blogs.each do |blog| %>
<tr>
<td><%= blog.title %></td>
<td><%= blog.post %></td>
<td><%= blog.user.username %></td> #blog.user_id works perfectly here.
<td><%= link_to 'Show', blog %></td>
<td><%= link_to 'Edit', edit_blog_path(blog) %></td>
<td><%= link_to 'Destroy', blog, method: :delete, data: { confirm:'sure?'} %></td>
</tr>
<% end %>
classblog
同时检查,可能是用户id指向不存在的用户记录。请检查您的博客表,查看每个创建的博客中是否存在用户id 同时检查您的用户模型,并根据所需关联进行更改 如果您使用的是一对一关系,那么您的用户模型应该具有
class User < ActiveRecord::Base
has_one :blog
end
class User < ActiveRecord::Base
has_many :blogs
end
您的users表是否有username列?您的
是否应该有一个:users
为单数?换句话说,班级博客应该有和\u one:user
。
Here is the create code:
# POST /blogs
# POST /blogs.json
def create
@blog = Blog.new(params[:blog])
@blog.user_id = current_user
respond_to do |format|
if @blog.save
format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
format.json { render json: @blog, status: :created, location: @blog }
else
format.html { render action: "new" }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end
class Blog < ActiveRecord::Base
attr_accessible :post, :title
#has_one :users // remove this line of code..
belongs_to :user
end
class User < ActiveRecord::Base
has_one :blog
end
class User < ActiveRecord::Base
has_many :blogs
end
class Blog < ActiveRecord::Base
attr_accessible :post, :title
belongs_to :user
end
def create
@blog = Blog.new(params[:blog])
@blog.user_id = current_user.id
respond_to do |format|
if @blog.save
format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
format.json { render json: @blog, status: :created, location: @blog }
else
format.html { render action: "new" }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end