2015-02-10 45 views
0

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

我一直在尋找這個問題的解決方案,但似乎沒有一個明顯的...任何人都可以請這個情況幫助我,而不必打破淺層嵌套資源?

回答

1

正確的方法是你的第二次嘗試。如果@article.usernil,這是因爲@article沒有user

確保您展示的文章有用戶。

可以是一個很好的選擇,這存在驗證添加到Article類: - > @ article.user = @user我創建行動

class Article < ActiveRecord::Base 
    #... 
    validates :user, presence: true 
    #... 
end 
+0

即使與validattion線,我的這篇文章似乎不具有用戶訪問.... T.T – Sardonic 2015-02-11 23:13:09

0

好吧,我加入了一行解決了這一問題。

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