我目前使用Rails 4創建一個網站,並且需要在模型「發佈」內使用另一個模型「響應」爲模型「候選人」創建一個窗體, 。在另一個控制器的顯示內部爲控制器創建一個窗體
此樁模型:
class Post < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
belongs_to :entrepreneur
belongs_to :categorie
has_many :candidatures
accepts_nested_attributes_for :candidatures
has_many :questions
accepts_nested_attributes_for :questions,
:reject_if => lambda { |a| a[:enonce].blank? },
:allow_destroy => true
end
的候選型號:
class Candidature < ActiveRecord::Base
has_many :reponses
accepts_nested_attributes_for :reponses, :allow_destroy => true
end
而且效應初探模型:
class Reponse < ActiveRecord::Base
belongs_to :candidature
end
我沒有參選和效應初探控制器,因爲我不認爲我需要任何東西(如果我錯了,請糾正我)。 我已經創建了項目的帖子,並且在帖子的顯示視圖中,我需要創建一個表單,客人可以通過答案回答一些問題,並且所有這些答案都必須保存在一個候選人中。
的schema.rb看起來像這樣:
ActiveRecord::Schema.define(version: 20130718083016) do
create_table "candidatures", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
end
create_table "questions", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
t.text "enonce"
end
create_table "reponses", force: true do |t|
t.integer "candidature_id"
t.datetime "created_at"
t.datetime "updated_at"
t.text "enonce"
end
create_table "posts", force: true do |t|
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
t.text "defi"
t.text "mission"
t.text "competences"
t.text "gain"
t.text "lieny"
t.text "liendb"
t.string "link"
end
爲崗位控制器:
class PostsController < ApplicationController
layout :resolve_layout
include Candidaturetopost
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Successfully created project."
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
@post.candidatures.build
end
def index
@posts = Post.all
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :image, :defi, :mission, :competences, :gain, :lieny, :liendb, :link, questions_attributes: [:enonce, :post_id, :id, :_destroy],
candidatures_attributes: [:post_id, :id, reponses_attributes: [:candidature_id, :id, :enonce]])
end
顯示視圖我試圖讓工作:
<%= form_for @post do |f| %>
<%= f.fields_for :candidatures do |cform| %>
<ol>
<% for question in @post.questions %>
<li><%= question.enonce %></li>
<%= cform.fields_for :reponses do |rform| %>
<%= rform.text_area :enonce %>
<% end %>
<% end %>
</ol>
<%= cform.submit %>
<% end %>
<% end %>
隨着這裏顯示的代碼,enonce的text_area甚至沒有顯示。
我甚至想做甚麼?如果不是,我怎麼能有類似的東西?
您的模型結構過於複雜,您應該重新考慮它。 –