我的表单应如何在Rails中查看?

时间:2012-02-14 15:34:45

标签: ruby-on-rails activerecord views

我已将两个模型命名为。一个模型TopicPost模型的父级,PostTag模型共享HABTM关系。没有一个模型有验证。

我想收集一个复选框,在主题和标签模型上设置数据,同时以单一形式提交帖子。我试过的任何时候都会遇到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 %>

1 个答案:

答案 0 :(得分:0)

是的,如果您需要这种类型的嵌套URL,则需要在每个redirect_to中定义命名空间。如果您没有此命名空间,则不能使用此嵌套URL。