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 validatio开发者_运维技巧n throws out
undefined local variable or method `params' for #<Class:0x3c4ad30>
error.
How can I use params[:category]??
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.
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
精彩评论