开发者

Adding Categories to my Articles in my Rails app (Small Help)

开发者 https://www.devze.com 2022-12-24 00:21 出处:网络
I\'m currently building a semi-small ruby app for a project. The problem I\'m currently facing is the following:

I'm currently building a semi-small ruby app for a project. The problem I'm currently facing is the following:

I want to be Able to fit the Article into the Categories. I've already accomplish this by having two models. An article model with a foreign key of category_id and my Category model with the name of the category. With a has_one and belogs_to relationship. (We're assuming you can only fit an article into one category). Here's the piece of code.

This is the new method, where i create a new article and load up all the categories.

def new  
 @article = Article.new  
 @categories = Category.find(:all)  
end

The problem comes when i try to get the category from a combo box in order to insert it along with the article.

This is the combo box code :

f.select(:category_id,@categories)

And this is the create method:

def create  
  @category = Category.find(params[:id])  
  @article = @category.articles.new(params[:article])  

  if @article.save  
    flash[:notice] = "Article Submitted Sucessfully"  
    redirect_to user_path  
  else  
    render :action => 'new'  
  end  
end  

开发者_JS百科I believe that the problem i have is in this line when i try to load up the selected category "@category = Category.find(params[:id])" because whenever i hardcode the this line into

@category = Category.find(1)

It Works perfectly


The problem lies with f.select. The second parameter doesn't set the value of the list of options to the id of the category. The form builder's select methods are kinda lacking. I would do this instead:

<%= collection_select :article, :category_id, @categories, :id, :name, @article.category_id %>

and that should get the right value to the controller.

Then in the controller, you can replace:

@category = Category.find(params[:id])  
@article = @category.articles.new(params[:article])  

with

@article = Article.new(params[:article])

The category_id will come from the params and be set correctly.

0

精彩评论

暂无评论...
验证码 换一张
取 消