У меня есть имена двух моделей. Одна модель Topic
является родительской для модели Post
, а Post
делится отношениями HABTM с моделью Tag
. Ни одна из моделей не имеет валидаций.Как должна выглядеть моя форма в Rails?
Я хотел бы использовать флажок, чтобы установить данные о теме и теге, пока вы отправляете сообщение в одной форме. Каждый раз, когда я пытался, я столкнулся с this problem.
Вопросы у меня есть:
- Как я должен увеличить свою форму, контроллер и модель, чтобы избежать ошибки, обнаруженные в this post?
- Должен ли я объявить свое пространство имен в каждом redirect_to?
Код контроллера
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