0
名前空間には2つのモデルがあります。 1つのモデルTopic
はPost
モデルの親であり、Post
モデルはTag
モデルとのHABTM関係を共有します。いずれのモデルにもバリデーションはありません。私のフォームはどのようにしてRailsで見えますか?
トピックとタグモデルのデータを設定するチェックボックスを使用して、1つのフォームで投稿を送信したいと思います。しかし私はいつでも私はthis problemを実行しようとしました。私が持っている
質問:
- どのように私はthis postで見つかったエラーを回避するために、私のフォーム、コントローラとモデルを拡張する必要がありますか?
- 各リダイレクトで自分のネームスペースを宣言する必要はありますか?
コントローラー・コードここで
before_filter :check_authentication, only: [:new]
before_filter :fetch_author, only: [:new, :create]
before_filter :fetch_post, only: [:show, :update, :edit, :destroy]
before_filter :fetch_topic, except: [:create]
def new
@topic = Topic.all
@post = @user.posts.build
@tag = @post.tags.build
end
def create
@post = @user.posts.build(params[:post])
@topic = @post.topic.build(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to [@topic, @post], notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
def update
if @post.update_attributes(params[:post])
redirect_to [@topic, @post], notice: 'Post was successfully updated.'
else
render :edit
end
end
def destroy
@post.destroy
redirect_to root_url([@topic, @post]), notice: 'Post deleted.'
end
private
def fetch_author
@user = User.find(session[:user_id])
end
def fetch_topic
@topic = Topic.find(params[:topic_id])
end
def fetch_post
@post = @topic.posts.find(params[:id])
end
は私のフォームは
<%= form_for([:blog, @topic, @post]) do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content, sanitize: true, rows: 15%>
</div>
<div class="field">
<%= f.fields_for(:topic) do |build| %>
<%= build.label :topic_name, "Select a topic" %>
<%= collection_select(:post, :topic_id, Topic.all - [@post], :id, :topic_name, prompt: true) %>
<%end%>
</div>
<div class="field">
<%= f.fields_for(:tags) do |build| %>
<%= unless build.object.new_record?
build.check_box('_destroy') + build.label('_destroy', 'Remove Tag')
end%>
<%= build.label :tag_name, "Add Tag"%>
<%= build.text_field :tag_name %>
<%end%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
ありがとうございます、私の主な質問に対する考えは大変高く評価されています。 – rhodee