> I asked a question on stackoverflow.com but did not get a wanted
> answer... So I am asking here.
> [http://stackoverflow.com/questions/4037020/rails-3-model-associations]
>
> 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?
Yes. This is perfectly normal. Generate a scaffold as a test and look at the code. It does exactly this.
> because I believe since models cannot access params
> variable, controller has to do the above job, and thats not 'rails way'
Sure it is. Your controller is performing an action on the model. That's the controllers job... to pass data into the model so the model can pass it into the database (for example).
What you *don't* want in your controller is any raw sql. Or any other business logic that could be encapsulated within the model to be reused elsewhere.
-philip
> 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.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment