user482594
user482594

Reputation: 17486

How can use 'params' with in model validation?

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.

Upvotes: 0

Views: 2016

Answers (1)

monocle
monocle

Reputation: 5896

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

Upvotes: 2

Related Questions