两个模型之间的关联

时间:2017-02-14 20:55:29

标签: ruby-on-rails associations

感谢您的光临。我目前正在构建一个拥有3个模型的博客应用程序。将发表评论的用户,文章和评论。我希望有人可以帮我解释一下我哪里出错了,以及如何更好地联系模型。我得到的当前错误是未定义的方法`用户'在文章#new controller。

我目前的代码是:

模式

create_table "articles", force: :cascade do |t|
    t.string   "title"
    t.text     "body"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
 end

 create_table "comments", force: :cascade do |t|
    t.text     "body"
    t.integer  "post_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["post_id"], name: "index_comments_on_post_id"
    t.index ["user_id"], name: "index_comments_on_user_id"
 end

 create_table "users", force: :cascade do |t|
    t.string   "username"
    t.string   "email"
    t.string   "password_digest"
    t.text     "about_me"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
 end

模型

class User < ApplicationRecord
 has_secure_password
 has_many :articles
 has_many :comments
end

class Article < ApplicationRecord
 belongs_to :user
 has_many :comments

 validates :user_id, presence: true
end

class Comment < ApplicationRecord
 belongs_to :post
 belongs_to :user
end

控制器

class ArticlesController < ApplicationController
 before_action :find_article, only: [:show, :edit, :update, :destroy]

 def index
  @articles = Article.all
 end

 def new
  @article = Article.new
 end

 def create
  @user = User.find(params[:user_id])
  @article = @user.articles.create(article_params)
  if @article.save
    redirect_to articles_path
  else
    redirect_to new_article_path
  end
 end

 def show
 end

 def edit
 end

 def update
  if @article.update(article_params)
    redirect_to :back
  else

  end
 end

 def destroy
  if @article.destroy
    flash[:notice] = "Successfully destroy the article"
    redirect_to @article
  else
    flash[:alert] = "Couldnt delete article"
    redirect_to :back
  end
 end

 private

 def find_article
  @article = Article.find(params[:id])
 end

 def article_params
  params.require(:article).permit(:title, :body)
 end
end

视图

<%= form_for(@article, @article.users.build) do |f| %>
 <%= f.label :title %>
 <%= f.text_field :title %>
 <%= f.label :body %>
 <%= f.text_field :body %>
 <%= f.submit %>
<% end %>

路线

root 'users#index'

resources :users
resources :articles do
 resources :comments
end

如果还有别的东西我可能会遗漏,以帮助解释我做错了什么以及如何改善/理解关联和建立/创造。请让我知道,我会添加其他信息。

对于每个教我/帮助我的人,非常感谢你。

1 个答案:

答案 0 :(得分:1)

你的表格应该是

<%= form_for @article do |f| %>

然后在控制器中

def create
  @article = current_user.articles.build(article_params)

  if @article.save
    redirect_to articles_path
  else
    redirect_to new_article_path
  end
end