所以,首先我有這個協會在我的項目正在進行: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