我是Ruby和Rails的新手,正在构建一个Web应用程序,我需要使用form_for将数据提交到我的数据库。我知道我错过了Rails MVC逻辑的一个关键概念,需要帮助缩小差距。我有一个大学对象,有很多帖子。我正在尝试从form_for传递数据,但也包括可以使用params哈希从URL中删除的数据。这是我的代码:
Posts_Controller.rb:
class PostsController < ApplicationController
def new
@college = College.find(params[:college_id])
@post = Post.new(:college_id => @college.id)
@title = "Submit Post"
end
def create
@post = Post.new(params[:post])
if @post.save
redirect_to root_path, :flash => { :success => "Post Submitted Successfully!" }
else
@title = "Submit Post"
render 'new'
end
end....
routes.rb中:
MyApp::Application.routes.draw do
get "sessions/new"
resources :posts
resources :smacks
resources :redemptions
resources :users do
resources :microposts, :only => [:index]
member do
get :following, :followers
end
end
resources :sessions, :only => [:new, :create, :destroy]
resources :microposts, :only => [:create, :destroy]
resources :relationships, :only => [:create, :destroy]
resources :colleges, :only => [:new, :create, :index, :show] do
resources :posts
resources :smacks
resources :redemptions
end
match '/signup', :to => 'users#new'
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/contact', :to => 'pages#contact'
match '/about', :to => 'pages#about'
match '/help', :to => 'pages#help'
查看新帖子,new.html.erb:
<h1>Submit a <%= @college.name %> Post</h1>
<%= form_for @post do |f| %>
<%= render 'fields', :f => f %>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
从new.html.erb调用'fields'文件:
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :type %><br />
<%= f.text_field :type %>
</div>
<div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content_type %><br />
<%= f.text_field :content_type %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
表单提交没有问题,但它只发布form_for中包含的字段。我想传递更多数据,例如在new_post页面的URL中的college_id。以下是URL在新页面上显示的内容:“http:// localhost:3000 / schools / 1 / posts / new”。我想将URL中的“1”传递给我的post db中的college_id字段。如果我需要发布任何代码,请告诉我是否有人可以提供帮助并告诉我。
谢谢!
答案 0 :(得分:0)
您可以采用的一种方法是在表单中添加<%= f.hidden_field(:college_id, @college.id) %>
。这应该使用正确的ID填充您的表单,然后我相信您的帖子模型具有属性belongs_to :college
。
我个人不推荐这种处理嵌套对象的方法。请查看以下网络广播并根据您的需要更改实施: http://railscasts.com/episodes/196-nested-model-form-part-1