所以,首先我有这个协会在我的项目正在进行:Rails,如何通过浅层嵌套资源中的子对象访问belongs_to(父)对象?
的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
我需要@user变量在我show.html.erb,出于各种原因,链接回用户的文章索引页。
有没有什么办法可以通过@article对象检索@user对象???
我一直在寻找这个问题的解决方案,但似乎没有一个明显的...任何人都可以请这个情况帮助我,而不必打破浅层嵌套资源?
即使与validattion线,我的这篇文章似乎不具有用户访问.... T.T – Sardonic 2015-02-11 23:13:09