我有user
模型和shout
模型。我想让一个用户与一个呼喊相关联。我没有在创建shouts表时建立这种关联,所以我不得不运行一个新的迁移。下面是我的表,每个的模型,以及从我的控制台输出的命令,我运行命令试图找到喊叫的user_id。你能看出我做错了吗?
模式:
create_table "shouts", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "user_id"
end
add_index "shouts", ["user_id"], name: "index_shouts_on_user_id"
create_table "users", force: :cascade do |t|
t.string "email", null: false
t.string "password_digest", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
end
用户模型:
class User < ActiveRecord::Base
validates :email, presence: true, uniqueness: true
validates :password_digest, presence: true
has_many :shouts
end
喊声模特:
class Shout < ActiveRecord::Base
belongs_to :user
end
呼喊控制器:
类ShoutsController&lt; ApplicationController中
def new
@new_shout = Shout.new
end
def create
@new_shout = Shout.new(shouts_params)
if @new_shout.user_id == nil
render new_shout_path
elsif @new_shout.save
redirect_to dashboard_path
else
render new_shout_path
end
end
private
def shouts_params
params.require(:shout).permit(:title, :description, :user_id)
end
端
一些测试代码:
> Shout.find(4)
> #<Shout id: 4, title: "four", description: "four", user_id: nil>
从控制台创建用户实例,正在运行:
> User.first.shouts.create(title: 'four', description: 'four')
>[["title", "four"], ["description", "four"], ["user_id", 1]
迁移文件:
class AddUserRefToShouts < ActiveRecord::Migration
def change
add_reference :shouts, :user, index: true, foreign_key: true
end
end
答案 0 :(得分:0)
如果你不想遵循评论中建议的方法,这里有一些公认的hacky选项(但它们会起作用)。您可以将user_id作为隐藏字段传递,因此它将包含在参数中,或者您可以在创建操作中明确设置它。
如果你想作为隐藏字段传递,请在你的喊叫表格中添加:
<%= f.hidden_field :user_id, value: current_user.id %>
或者,如果您想要处理创建操作:
def create
@shout = Shout.new(shout_params)
@shout.user_id = current_user.id
@shout.save
end