0

Apparently, I am using params[:category] (from routing...) to categorize some articles within same table, and I just want to set the category column of an article to be params[:category]. I tried just saying

class Article < ActiveRecord::Base
  has_many :comments
  belongs_to :article_category # this is the model that has info about categories
  category = params[:category]
end

but above validation throws out

undefined local variable or method `params' for #<Class:0x3c4ad30>

error.

  1. How can I use params[:category]??

  2. Also, how can I be assure that params[:category] will be one of categories listed in article_categories database table? I don't want user to mannually type in the address for random category and insert it in the table.

1
  • You really need to go through the basics of MVC. Query parameters are only available in controller actions, as controllers handle all HTTP requests. Can you be more specific on what you are trying to do? Commented Oct 25, 2010 at 21:46

1 Answer 1

2

If an Article has an attribute :category, then when you do

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

the category attribute should be set automatically. It sounds like you just need to create your view to send the category field as part of the article form.

<%= form_for @article do |f| %>
  <%= f.text_input :category %>
  ...

This should give you the param you want:

params[:article][:category]

If Category is a separate model, then you can use a nested form. See http://railscasts.com/episodes/196-nested-model-form-part-1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.