rails 4 用户评论用户如何做到这一点 [英] rails 4 users reviews for users how to do this

查看:39
本文介绍了rails 4 用户评论用户如何做到这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为用户创建评论,如何更好地创建数据库和活动记录关联,我正在考虑创建模型评论、带有内容字符串的评论表和带有 2 个字符串 user_id、user_id、创建评论的第一个字符串的 users_users 表和第二个为谁创建了评论,还是这种错误的方式?

解决方案

虽然你的问题很模糊,但我猜你对 Rails 很陌生,所以我想我会为你写这篇文章

<小时>

用户有_许多评论

我觉得你需要关于 或者在reviews控制器中,可以合并当前用户的user_id给外键"赋值(user_id) 列 ActiveRecord 在其关联中使用

后者解释起来最直接,所以我给你演示:

#app/controllers/reviews_controller.rb定义新@review = Review.new结尾定义创建@review = Review.new(review_params)@review.save结尾私人的def review_paramsparams.require(:review).permit(:title, :body).merge(:user_id => current_user.id)结尾#app/views/reviews/new.html.erb<%= form_for @review do |f|%><%= f.text_field :title %><%= f.text_field :body %><%结束%>

这将使用附加的 user_id 保存您发布的评论,然后您可以使用诸如 @user.reviews

之类的内容调用它

希望这有帮助吗?

i want create reviews for users from users, how better create db and Active Record Associations, i am thinking of create model reviews, reviews table with content string and table users_users with 2 strings user_id, user_id, first string who create review and second for whom created review, or this wrong way?

解决方案

Although your question is very vague, I'm guessing you're quite new to Rails, so I thought I'd write this post for you


User has_many Reviews

Sounds to me like you need help with ActiveRecord associations, which will allow you to create Reviews from Users

Specifically, you'd want to use the has_many relationship, so that a user has_many reviews:

You'd set up 2 models like this:

#app/models/review.rb
class Review < ActiveRecord::Base
    belongs_to :user
end

#app/models/user.rb
class User < ActiveRecord::Base
    has_many :reviews
end

This will allow you to call the User's ActiveRecord objects like this:

#app/controllers/users_controller.rb
def index
   @user = User.find(params[:id])
   @reviews = @user.reviews
end


Saving Reviews to Users

Having this setup will allow you to save reviews to specific users

To do this, you'll be able to either use accepts_nested_attributes_for or in the reviews controller, you can merge the user_id of the current user to assign a value to the "foreign key" (user_id) column ActiveRecord uses in its association

The latter is the most straightforward to explain, so I'll give you a demo:

#app/controllers/reviews_controller.rb
def new
    @review = Review.new
end

def create
    @review = Review.new(review_params)
    @review.save
end

private
def review_params
    params.require(:review).permit(:title, :body).merge(:user_id => current_user.id)
end


#app/views/reviews/new.html.erb
<%= form_for @review do |f| %>
    <%= f.text_field :title %>
    <%= f.text_field :body %>
<% end %>

This will save the review you post with an attached user_id, which you can then call with something like @user.reviews

Hope this helps?

这篇关于rails 4 用户评论用户如何做到这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆