I asked a question on stackoverflow.com but did not get a wanted answer... So I am asking here. [ruby - Rails 3 model associations - Stack Overflow]
I am making a simple BBS system with ruby on rails3.
There are 3 main models, which 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. I used a session to create a current_member.
Now, what should I do if I want to automatically fill a category_id column of an article?? Is there something like
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.