我無法添加對象來關聯類。 父級用戶與廣告類具有has_many關係。 當我嘗試從廣告控制器訪問用戶的has_many對象「:ads」時,它會返回「undefined method ads」異常。我在下面發佈我的模型和我的控制器代碼。請幫我解決這個問題。將對象添加到一對多關係ROR
用戶模型
class User < ActiveRecord::Base
has_many :ads
has_secure_password
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "50x50#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
def self.searchID(query)
where("id like ?", "#{query}")
end
end
廣告模式
class Ad < ActiveRecord::Base
belongs_to :user
scope :orderNewestFirst , lambda { order("id DESC") }
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
def self.search(query)
where("title like ?", "%#{query}%")
end
end
廣告控制器
class AdController < ApplicationController
layout false
before_action :confirm_logged_in
def index
@ads = Ad.orderNewestFirst
end
def new
@ad = Ad.new()
end
def create
@find = session[:user_id]
@user = User.searchID(@find)
@ad = Ad.new(ad_params)
if @user.ads << @ad #***this is where the error is occuring***
flash[:notice] = "Ad created Successfully"
redirect_to(:controller => 'user' , :action => 'index')
else
render('new')
end
end
def show
@ad = Ad.find(params[:id])
end
def ad_params
params.require(:ad).permit(:title, :category, :description , :priceRange, :avatar)
end
end
編輯
這裏AR Ë我遷移用戶和廣告
用戶遷移
class CreateUsers < ActiveRecord::Migration
def up
create_table :users do |t|
t.string "firstName" , :limit => 50 , :null => false
t.string "lastName" , :limit => 50
t.string "email" , :null => false
t.string "password" , :limit => 30 , :null => false
t.integer "rating" , :default => 0
t.string "location" , :default => "Lahore"
t.timestamps null: false
end
end
def down
drop_table :users
end
end
#user = User.new(:firstName => "" , :lastName => "" , :email => "" , :password => "" , :rating => "" , :location => "")
廣告遷移
class CreateAds < ActiveRecord::Migration
def up
create_table :ads do |t|
t.references :user
t.string "title" , :null => false
t.string "category" , :null => false
t.text "description"
t.string "priceRange" , :null => false
t.attachment :avatar
t.timestamps null: false
end
add_index("ads" , "user_id")
end
def down
drop_table :ads
end
end
#ad = Ad.new(:title => "" , :category => "" , :description => "" , :priceRange => "")
,我得到的錯誤..
'ad'模型的表名是什麼?'ad'模型中有'user_id'列嗎? –
請發佈您的完整錯誤stacktrace。 – Pavan
@PramodShinde,我使用引用而不是user_id。 –