Rails: Show form from different model in a view

浪子不回头ぞ 提交于 2019-12-01 02:22:19

问题


I have a location model and a post model. I want to allow the user to create new posts from the index page of the location model. How do I do that? I tried rendering the post new.html.erb as a partial in location index.html.erb, but this leads to errors as post new.html.erb references the @post variable.

How should I accomplish this?


回答1:


Try something like this

LocationController

def index
  @location = Location.find(:all)
  @post = Post.new
end

Now ur location view would have access to the instance variable @post. Render a partial using that

render :partial => 'posts/post', :object => @post



回答2:


You can start the form like this:

<%= form_for Post.new do ... %>



回答3:


Just create a @post variable in your action in the LocationsController.



来源:https://stackoverflow.com/questions/7188999/rails-show-form-from-different-model-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!