【问题标题】:How to create a multi-model, multi-page form in Rails?如何在 Rails 中创建多模型、多页面的表单?
【发布时间】:2011-09-25 03:10:55
【问题描述】:

我是一个尝试学习 Ruby on Rails 的新手。我正在尝试学习如何使用 has_many 关联。我有一个我希望能够添加 cmets 的博客。我可以在帖子页面中添加一个添加 cmets 表单,但我还想通过“添加 cmets 表单”转到一个新页面来了解如何添加 cmets。

但是,我无法传递有关评论所属帖子的必要信息。我不确定这是我的表单还是 cmets_controller 的问题。

posts_controller

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
  end
  def new
    @post = Post.new
  end
  def index
    @posts = Post.all
  end
end

cmets_controller

class CommentsController < ApplicationController
  def new
    @comment = Comment.new  
  end
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
end

评论模型

class Comment < ActiveRecord::Base
  belongs_to :post
end

发布模型

class Post < ActiveRecord::Base
  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  has_many :comments, :dependent => :destroy
  accepts_nested_attributes_for :comments
end

意见表

    <h1>Add a new comment</h1>
    <%= form_for @comment do |f| %>
      <div class="field">
        <%= f.label :commenter %><br />
        <%= f.text_field :commenter %>
      </div>
      <div class="field">
        <%= f.label :body %><br />
        <%= f.text_area :body %>
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

routes.rb

Blog::Application.routes.draw do
  resources :posts do
    resources :comments
  end
  resources :comments
  root :to => "home#index"
end

【问题讨论】:

    标签: ruby-on-rails forms has-many


    【解决方案1】:

    我猜你需要在你的 cmets 页面中包含帖子 ID。

    做这样的事情:

    当你重定向到 cmets 控制器时,传递 post id 并从 cmets 控制器获取它

    class CommentsController < ApplicationController
      def new
        @post_id = params[:id] 
        @comment = Comment.new  
      end
      def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(params[:comment])
        redirect_to post_path(@post)
      end
    end
    

    然后在您的 cmets/new.erb 视图中,将帖子 ID 添加为隐藏参数

    <h1>Add a new comment</h1>
    <%= form_for @comment do |f| %>
      <div class="field">
        <%= f.label :commenter %><br />
        <%= f.text_field :commenter %>
      </div>
      <div class="field">
        <%= f.label :body %><br />
        <%= f.text_area :body %>
      </div>
      <div class="actions">
        <%= f.submit %><%= f.text_field :post_id, @post_id  %>
      </div>
    <% end %>
    

    【讨论】:

    • 感谢您的回复,但我仍然卡住了。我知道我需要将 post_id 传递给 cmets 控制器,但我仍然无法使用正确的 post_id 保存评论。视图中隐藏的参数似乎打破了它。再次感谢。
    • 嗨@monz,我创建了一个非常简单的博客应用程序来演示您的解决方案,如果我有您的邮件,我可以通过电子邮件发送它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多