2015-02-10 50 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