Rails:使用表单将记录添加到具有belongs_to关联的模型

时间:2013-03-02 04:04:01

标签: ruby-on-rails-3 forms model-associations

我可以在我的视图result.html.erb中访问@result。 @result是一个Movie对象。我想通过表单为这个@result对象创建注释。我将评论框(表格)放在result.html.erb。

我对表单的语法不熟悉。我也很困惑在提交后将表单本身指向何处。我是否需要一起创建一个新的控制器以用于创建操作的注释?

我不确定如何创建此表单以便将其保存到@ result.comments.last

任何帮助将不胜感激!发表的是我的模特和控制器。

class Movie < ActiveRecord::Base
  attr_accessible :mpaa_rating, :poster, :runtime, :synopsis, :title, :year

  has_many :comments

end


class Comment < ActiveRecord::Base
  attr_accessible :critic, :date, :publication, :text, :url

  belongs_to :movie
end


class PagesController < ApplicationController

  def index
  end

  def search
    session[:search] = params[:q].to_s
    redirect_to result_path
  end

  def result
    search_query = search_for_movie(session[:search])
    if !search_query.nil? && Movie.find_by_title(search_query[0].name).nil?
      save_movie(search_query) 
      save_reviews(search_query)
    end
    @result ||= Movie.find_by_title(search_query[0].name)
  end
end

result.html.erb

我曾经使用过simple_form gem,因为我认为它会更好但我认为我的用例非常简单,只需使用标准的rails form helper。如果我错了,请纠正我。这是我到目前为止所写的内容:

<%= simple_form_for @result do |f| %>
  <%= f.input :text %>
  <%= f.input :critic %>
  <%= f.button :submit %>
<% end %>

我收到错误:

undefined method `movie_path' for #<#<Class:0x000001013f4358>:0x00000102d83ad0>

1 个答案:

答案 0 :(得分:0)

我最终在页面控制器中添加了#create操作,并将表单放在我的视图中:

        <%= form_for @comment, :url => { :action => "create" } do |f| %>
          <div class="field">
            <%= f.text_area :text, placeholder: "Compose new review..." %>
                <%= hidden_field_tag 'critic', "#{current_user.name}"  %>
                <%= hidden_field_tag 'date', "#{Time.now.strftime("%m/%d/%Y")}"  %>
          </div>
          <%= f.submit "Post", class: "btn btn-large btn-primary" %>
        <% end %>

在控制器页面控制器中

  def create
    search_query = search_for_movie(session[:search])
    @movie = Movie.find_by_title(search_query[0].name)
    @comment = @movie.comments.create(text: params[:comment][:text], critic: params[:critic], date: params[:date])
    if @comment.save
      flash[:success] = "Review added!"
      redirect_to result_path
    else
      redirect_to result_path
    end
  end