views:

48

answers:

2

Hello All,,

I have problem in my controller page. Btw i want to execute localhost:3000/article/donat?author_id=4, this mean i want to get on view only article with author_id = 4 i have tried type code like this.

def donat
    @title = "All blog entries"
    if params[:author_id] == :author_id
      @articles = Article.published.find_by_params(author_id)
    else
      @articles = Article.published
    end
    @articles = @articles.paginate :page => params[:page], :per_page => 20
    render :template => 'home/index'
  end

It is not working. Have you any suggestion for this case?

+4  A: 

You want nested resources for this, and the getting started guide is a pretty good example of this.

Personally, I would put this at the top of my controller:

before_filter :find_author

And this at the bottom:

private 
  def find_author
     @author = Author.find(params[:author_id]) if params[:author_id]
     @articles = @author ? @author.articles : Article
  end

And then further up in the controller where I need to find articles:

@articles.find(params[:id])

Which will scope it appropriately.

Ryan Bigg
How does find_author get called here and @articles get set? Did you forget to mention that it will need to be in a before_filter?
rnicholson
Indeed, but Emfi fixed that up for me and I think I would still use them for the index and new actions.
Ryan Bigg
+1  A: 

You should do as Radar suggests (use nested resources), however this should fix your immediate problem:

def donat
  @title = "All blog entries"
  if params[:author_id]   # This is where the problem is.
    published_articles = Article.published.find_by_params(author_id)
  else
    published_articles = Article.published
  end
  @articles = published_articles.paginate :page => params[:page], :per_page => 20
  render :template => 'home/index'
end
jonnii