【发布时间】:2017-07-04 04:00:00
【问题描述】:
最初我有一个属于 User 模型的 Joke.rb 模型。笑话表有:笑话,:作者。它在使用@joke = current_user.jokes.new(joke_params) 时运行良好,但我将 :author 从笑话模型中取出并使其成为自己的模型,因此当用户创建笑话时,我可以为每个作者制作虚荣 URL/动态路由。这是我现在拥有的:
用户型号:has_many :jokes
笑话模特:belongs_to :userhas_one :author
作者型号:has_many :jokes
这是我的架构:
ActiveRecord::Schema.define(version: 20170703173447) do
create_table "authors", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "jokes", force: :cascade do |t|
t.string "joke"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
这是我的笑话控制器:
class JokesController < ApplicationController
before_action :set_joke, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index]
def index
@joke = Joke.order("Random()").first
end
def my_jokes
@jokes = current_user.jokes.all
end
def new
@joke = current_user.jokes.new
end
def create
@joke = current_user.jokes.new(joke_params)
if @joke.save
redirect_to root_path, notice: 'Joke was successfully added!'
else
render :new
end
end
def update
if @joke.update(joke_params)
redirect_to root_path, notice: 'Joke was successfully updated.'
else
render :edit
end
end
def destroy
@joke.destroy
redirect_to my_jokes_path, notice: 'Joke was successfully deleted.'
end
def edit
end
def about
end
private
def joke_params
params.require(:joke).permit(:joke, :name)
end
def set_joke
@joke = Joke.find(params[:id])
end
end
在 Rails 控制台中,调用 Author 或 Joke 时,两者都没有关联。
我尝试了很多不同的东西,但我无法让它发挥作用。我在这里和教程中遵循了许多半相关问题的答案,但我很烂。请帮忙,谢谢! :)
【问题讨论】:
-
什么意思在rails控制台中,调用Author或者Joke时,两者都没有关联。?
-
例如:
2.4.0 :008 > Author => Author(id: integer, name: string, created_at: datetime, updated_at: datetime)如果我这样做 Author.jokes 我得到一个错误。 -
错误是什么?
-
NoMethodError: undefined methodjokes' for #<0x007fbefa5c4160>0x007fbefa5c4160>
标签: ruby-on-rails devise associations models