【发布时间】:2016-04-14 04:00:24
【问题描述】:
我正在使用设计,现在我正在尝试将用户与文章相关联。
我阅读了几篇关于 stackoverflow 的文章,但我很难理解它在我的应用程序中是如何工作的。我试图理解this question 但这似乎是黑魔法......
数据库:MongoDB(mongoid gem)
这是我所拥有的:
article_controller.rb
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
# GET /articles
# GET /articles.json
def index
@articles = Article.all
end
# GET /articles/1
# GET /articles/1.json
def show
end
# GET /articles/new
def new
@article = Article.new
end
# GET /articles/1/edit
def edit
end
# POST /articles
# POST /articles.json
def create
@article = Article.new(article_params)
respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render action: 'show', status: :created, location: @article }
else
format.html { render action: 'new' }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /articles/1
# PATCH/PUT /articles/1.json
def update
respond_to do |format|
if @article.update(article_params)
format.html { redirect_to @article, notice: 'Article was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
# DELETE /articles/1
# DELETE /articles/1.json
def destroy
@article.destroy
respond_to do |format|
format.html { redirect_to articles_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
@article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:title, :content)
end
end
article.rb
class Article
include Mongoid::Document
belongs_to :user
field :title, type: String
field :content, type: String
field :user, type: String
default_scope -> { order(created_at: :desc) }
end
用户.rb
class User
include Mongoid::Document
has_many :articles
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# ... devise configurations
end
我对如何正确地做到这一点了解不足。
【问题讨论】:
标签: ruby-on-rails ruby mongodb devise