Scope question in Rails
I'm new to rails and having issues with scope. I have two classes, Post and Story. each instance of Post is created with data from a form on the Story show page. One of the parameters for Post is the id of the instance of Story from which it was created. I don't know how to get this id. @story is nil eve开发者_JS百科n if I defined it in the controller under def show
as @story=Story.find(params[:id])
Thanks!
It really depends on where you're creating the post, and the routing for the controllers. I'm hoping this is in a PostsController, not StoriesController - as it doesn't really belong in the latter.
And so, presuming you're using PostsController, the best approach (given every post is tied to a Story, it sounds), is to have this controller nested within stories in your routes.rb
file:
resources :stories do
resources :posts
end
Then, the story id (given the form is set up correctly) is available in params[:story_id]
- and creation could look something like this:
story = Story.find params[:story_id]
post = story.posts.create params[:post]
Working off a few assumptions here, but hopefully this is helpful.
精彩评论