Rails关联不起作用,user_id没有显示在控制台中

时间:2016-08-04 12:46:12

标签: mysql ruby-on-rails devise associations

在控制台中我收到此错误:

var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
    modal.style.display = "block";
}
span.onclick = function() {
    modal.style.display = "none";
}
document.body.addEventListener('click', function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
});

此外,当我尝试在控制台中访问Peegin时,它不会显示peegin.user NameError: undefined local variable or method `peegin' for main:Object Did you mean? @peegin

user_id

用户类

Peegin
 => Peegin(id: integer, title: string, meaning: string, example: string, created_at: datetime, updated_at: datetime, permalink: string) 
2.3.0 :039 >

Peegin Class

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

has_many :peegins
end

模式

class Peegin < ActiveRecord::Base
belongs_to :user
before_create :generate_permalink
def to_param
    permalink
end



private

def generate_permalink
    pattern=self.title.parameterize
    duplicates = Peegin.where(permalink: pattern)

    if duplicates.present?
        self.permalink = "#{pattern}-#{duplicates.count+1}"
    else
        self.permalink = self.title.parameterize
    end

 end

end

2 个答案:

答案 0 :(得分:0)

确保您的数据库是最新的。

$ bin/rake db:migrate

然后..你必须创建一个Peegin对象然后你可以访问用户:

peegin = Peegin.create(title: "something")
peegin.user # => nil
peegin.user = User.first # Or take any user you want.
peegin.save # => user_id is updated in the database

答案 1 :(得分:0)

在您的rails控制台中,请尝试以下操作:

@peegin = Peegin.find(1) //IF one doesn't work make sure if database has a record with this id and try with id that exists.

然后使用

@peegin.user 

而不是

peegin.user