Rails 4:模型关联不起作用

时间:2017-04-20 23:28:01

标签: ruby ruby-on-rails-4 associations

我在Rails 4中的关联无法正常工作

review.rb

class Review < ActiveRecord::Base
  belongs_to :movie, :class_name => "Movie", :foreign_key => "movie_id"
  belongs_to :moviegoer
  # review is valid only if it's associated with a movie:
  validates :movie_id, :presence => true
  # can ALSO require that the referenced movie itself be valid
  #  in order for the review to be valid:
  validates_associated :movie

end

movie.rb

class Movie < ActiveRecord::Base
  has_many :reviews
  before_save :capitalize_title

  def capitalize_title
    self.title = self.title.split(/\s+/).map(&:downcase).
      map(&:capitalize).join(' ')
  end

  scope :with_good_reviews, lambda { |threshold|
    Movie.joins(:reviews).group(:movie_id).
      having(['AVG(reviews.potatoes) > ?', threshold.to_i])
  }
  scope :for_kids, lambda {
    Movie.where('rating in (?)', %w(G PG))
  }

  scope :recently_reviewed, lambda { |n|
    Movie.joins(:reviews).where(['reviews.created_at >= ?', n.days.ago]).uniq
  }

  def self.all_ratings ; %w[G PG PG-13 R NC-17] ; end #  shortcut: array of strings

  validates :title, :presence => true
  validates :release_date, :presence => true
  validate :released_1930_or_later # uses custom validator below
  validates :rating, :inclusion => {:in => Movie.all_ratings},
    :unless => :grandfathered?

  def released_1930_or_later
    errors.add(:release_date, 'must be 1930 or later') if
      release_date && release_date < Date.parse('1 Jan 1930')
  end

  @@grandfathered_date = Date.parse('1 Nov 1968')

  def grandfathered?
    release_date && release_date < @@grandfathered_date
  end
end

reviews_controller.rb

class ReviewsController < ApplicationController
  before_filter :has_moviegoer_and_movie, :only => [:index, :new, :create]
  protected
  def has_moviegoer_and_movie
    unless @current_user
      flash[:warning] = 'You must be logged in to create a review.'
      redirect_to '/auth/twitter'
    end
    unless (@movie = Movie.where(:id => params[:movie_id]))
      flash[:warning] = 'Review must be for an existing movie.'
      redirect_to movies_path
    end
  end
  public

  def index
    @reviews = @movie.reviews
    render(:partial => 'review', :object => @reviews) if request.xhr?
  end

  def new
    @review = @movie.reviews.build
  end
  def create
    # since moviegoer_id is a protected attribute that won't get
    # assigned by the mass-assignment from params[:review], we set it
    # by using the << method on the association.  We could also
    # set it manually with review.moviegoer = @current_user.
    @current_user.reviews << @movie.reviews.build(params[:review])
    redirect_to movie_path(@movie)
  end
end

在审核控制器中,当我尝试访问@ movie.reviews时,它应该返回属于该电影的所有评论的列表,但相反,我收到一条错误,上面写着“电影的未定义方法'评论”错误。这里发生了什么?这应该是正常的吗?我也设置了一个嵌套路线

resources :movies do
  resources :reviews
end

1 个答案:

答案 0 :(得分:1)

该行:

require_once('./phpmailer/class.phpmailer.php'); # Files attached below
require_once('./phpmailer/class.smtp.php');

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPAuth   = true;
$mail->SMTPSecure = "tls";
$mail->Host       = "smtp.gmail.com"; 
$mail->Port       = 587;  
$mail->Username   = "someMailAddress@gmail.com";
$mail->Password   = "password";

$to = ('to@mail.com');
$subject = 'This is and test mail from PHPMailer';

$message = 'Hi';
$message .= 'this is an mail body';

$mail->SetFrom( 'info@stackoverflow.com' , 'Stack OverFlow' );
$mail->AddAddress( $to , 'Abdulla Nilam' );
$mail->Subject = $subject;
$mail->MsgHTML( $message );
$sendEmail = $mail->Send();

if( $sendEmail == true )
{
    $this->session->set_flashdata('success', 'It was sent ....');
    redirect('contact');
}
else
{
    $this->session->set_flashdata('error', 'Nah :/ something wrong');
    redirect('contact');
}

取代unless (@movie = Movie.where(:id => params[:movie_id])) 而不是记录实例。你应该这样做:

ActiveRecord_Relation

代替