RubyとRailsが初めてで、form_forを使用してデータベースにデータを送信する必要のあるWebアプリケーションを構築しています。私は、Rails MVCロジックの重要な概念が欠けていることを知っており、ギャップを埋める手助けが必要です。私はhas_many投稿のCollegeオブジェクトを持っています。私はform_forからデータを渡そうとしていますが、paramsハッシュを使用してURLから取り出せるデータも含んでいます。ここに私のコードです:RailsでのMVCを正しく使用してform_forでデータベースにデータを渡す
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を:
<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ため
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から呼び出されました:
<%= 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/colleges/1/posts/new」です。私は私のポストdbのcollege_idフィールドにURLから "1"を渡したいと思います。コードを投稿する必要がある場合は誰でも手伝って知らせてください。
ありがとうございます!