views:

58

answers:

1

I am making a simple BBS system with ruby on rails3.

3 main modesl are Members/Categories/Articles.

Article belongs to Members/Categories, (member_id/category_id columns in db table) and each member/category 'has_many' articles.

When a specific user tries to write an article, I tried it by

def new
  @article = current_member.articles.new
end

and that automatically filled in a member_id section when an article is created without any form input or anything.

Now, what should I do if I want to automatically fill a category_id column of an article?? I believe every data related jobs should be done within model. However, I am passing in :category value through url

For example,

localhost:3000/articles/qna/new

would mean the article should have an category_id of 2 (assuming category with id=2 has name=qna, also, I did routing jobs that I can successfully get 'qna' from params[:category]).

Should I use

 def create
   current_member.articles.build(:category => get_category_id_from_name(params[:category]))
 end 

? But is it okay? because I believe since models cannot access params variable, controller has to do the above job, and thats not 'rails way' I do not want to use nested form, because I do not want user to choose an category when they are writing. Its like, if there is a QnA board, and if user clicked 'write' button, that means user is writing in a QnA board.

+1  A: 

The easiest way to do this is to add two hidden fields on the form that creates the Article instance, and and assign the values you wish for "category_id" and "member_id" to those hidden fields.

Rails will automatically pull these into the params hash and they will automatically end up in your call to Article.new.

TreyE
Yeah I thought of that as well, but what if user uses ex)firefox, the change the hidden readonly-variable to something else??