2013-03-02 65 views
0

我可以在我的视图result.html.erb中访问@result。 @result是一个Movie对象。我想通过表单为这个@result对象创建注释。我在result.html.erb中放置注释框(表单)。Rails:使用表单将记录添加到具有belongs_to关联的模型

我是新来的形式的语法。我也对提交后将表单本身指向哪里感到困惑。我是否需要创建一个新的控制器一起为创建操作的意见?

我不知道如何使得它保存到@ 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宝石,因为我认为这将是更好,但我觉得我的使用情况是足够简单,只需使用标准轨形成帮手。如果我错了,请纠正我。这是我写的,到目前为止:

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

我收到的错误:

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

回答

0

我最终加入了#创建行动,页面控制器和放置形式,我的看法是:

 <%= 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 
相关问题