所以,首先,我在我的项目中进行了这种关联:
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变量,原因有多种,包括链接回用户的文章&#39;索引页面。
有什么方法可以通过@article对象???
检索@user对象我一直在寻找这个问题的解决方案,但似乎并不是一个明显的问题......任何人都可以帮助我解决这种情况,而不必打破浅层嵌套资源吗?
答案 0 :(得分:1)
正确的方法是你的第二次尝试。如果@article.user
为nil
,那是因为@article
没有user
。
确保您展示的文章有用户。
将此状态验证添加到Article
类:
class Article < ActiveRecord::Base
#...
validates :user, presence: true
#...
end
答案 1 :(得分:0)
好的,我通过添加一行修复了问题 - &gt; @ article.user = @user on my create action。
class ArticlesController < ApplicationController
def index
@articles = Article.all
@user = User.find(params[:user_id])
end
def new
@article = Article.new
@user = User.find(params[:user_id])
end
def create
@article = Article.new(allow_params)
@user = User.find(params[:user_id])
@article.user = @user
if @article.save
flash[:notice] = "You have successfully saved."
redirect_to article_path(@article)
else
render new_user_article_path(@user)
end
end
每当我需要@user时,我只是通过@ article.user
访问它