我想根据Hartl的教程实施用户评论。
我在Rails的控制台中执行此操作没有问题,但我遇到了表单问题。
表单可以保存但不保存内容:
INSERT INTO "reviews" ("reviewer_id", "reviewee_id", "created_at","updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["reviewer_id", 1], ["reviewee_id", 15], ["created_at", 2016-09-16 09:52:49 UTC], ["updated_at", 2016-09-16 09:52:49 UTC]]
这是用户模型:
has_many :active_reviews, class_name: "Review",
foreign_key:"reviewer_id",
dependent: :destroy
has_many :passive_reviews, class_name: "Review",
foreign_key:"reviewee_id",
dependent: :destroy
has_many :reviewing, through: :active_reviews, source: :reviewee
has_many :reviewers, through: :passive_reviews, source: :reviewer
def review(other_user, great)
active_reviews.create!(reviewee_id: other_user.id, content: great)
end
评论模型:
belongs_to :reviewer, class_name: "User"
belongs_to :reviewee, class_name: "User"
validates :reviewer_id, presence: true
validates :reviewee_id, presence: true
评论控制员:
class ReviewsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def create
@review = current_user.active_reviews.build
@user = User.find(params[:reviewee_id])
current_user.review(@user, :content)
redirect_to reviews_user_path(@user)
flash[:success] = "User reviewed"
end
def destroy
end
end
观看次数(shared / _review_form.html.erb):
<%= form_for(@review) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div><%= hidden_field_tag :reviewee_id, @user.id %></div>
<%= f.text_area :content, placeholder: "Leave a review..." %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
观看次数(users / user_reviews.html.erb):
<% provide(:title, @title) %>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= gravatar_for @user %>
<h1><%= @user.name %></h1>
<span><%= link_to "view my profile", @user %></span>
<span><b>Microposts:</b> <%= @user.microposts.count %></span>
</section>
<section class="user_info">
<%= render 'shared/review_form' %>
</section>
<% @reviews.each do |r| %>
<ol class="users follow">
<li><%= r.reviewer.name %>: <%= r.content %></li>
</ol>
<% end %>
</aside>
</div>
答案 0 :(得分:1)
我认为你没有打电话给'保存&#39;你的创建函数中的方法
例如:
def create
#---your code----
@reviews= Review.new(review_params)
if @review.save
redirect_to :action => 'list'
else
render :action => 'new'
end
end
答案 1 :(得分:0)
谢谢我已经弄明白了
我的内容未插入,因为它是评论中的哈希
"review"=>{"content"=>"fsdfsdfsdf"}
解决方案
def create
@user = User.find(params[:reviewee_id])
@review = Review.create!(reviewer_id: current_user.id, reviewee_id:@user.id, content: params[:review][:content])
if @review.save
redirect_to reviews_user_path(@user)
flash[:success] = "User reviewed"
end
end
def destroy
end