【问题标题】:Rails: Using a form to add records to a model that has a belongs_to associationRails:使用表单将记录添加到具有 belongs_to 关联的模型
【发布时间】:2013-03-02 04:04:01
【问题描述】:

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

我不熟悉表单的语法。我也对提交后将表单本身指向何处感到困惑。我是否需要通过创建操作为 cmets 一起创建一个新控制器?

我不确定如何创建此表单以便将其保存到 @result.cmets.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 表单助手即可。如果我错了,请纠正我。以下是我目前写的内容:

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

我收到错误消息:

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

【问题讨论】:

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


    【解决方案1】:

    我最终向页面控制器添加了一个#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 %>
    

    在控制器Pages控制器中

      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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多