所以,首先我在我的项目中进行了这种关联:
的routes.rb
resources :users do
resources :articles, only: [:new, :index, :create]
end
resources :articles, only: [:show, :edit, :update, :destroy] do
resrouces :comments
end
article.rb
class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
validates :title, presence: true,
length: { minimum: 5 }
validates :text, presence: true,
length: { in: 1..200 }
end
user.rb
class User < ActiveRecord::Base
has_many :articles, dependent: :destroy
other codes..
end
所以基本上是一个浅的嵌套资源 . 我遇到的问题是在我的articles_controller.rb中:
class ArticlesController < ApplicationController
def index
@articles = Article.all
@user = User.find(params[:user_id]) #This works fine.
end
def new
@article = Article.new
@user = @User.find(params[user_id]) #This works fine.
end
def show
@article = Article.find(params[:id])
@user = User.find(params[:user_id]) #@user = nil, because show action is not in the nested resource, thus :user_id is not available??
@user = @article.user #@user = nil, again....
end
other codes...
end
我需要在show.html.erb中使用@user变量,原因有多种,包括链接回用户文章的索引页面 .
有什么办法可以通过@article对象检索@user对象吗?
我一直在寻找这个问题的解决方案,但似乎没有明显的问题......任何人都可以帮助我解决这种情况,而不必打破浅层嵌套资源?
2 回答
好的,我通过在我的创建操作上添加一行 - > @ article.user = @user来解决问题 .
每当我需要@user时,我只是通过@ article.user访问它
正确的方法是你的第二次尝试 . 如果
@article.user
是nil
,那是因为@article
没有user
.确保您显示的文章有用户 .
可以是一个很好的选择将此状态验证添加到
Article
类: