我在将对象添加到关联类时遇到问题。 父类 user 与广告类具有 has_many 关系。 当我尝试从广告 Controller 访问用户的 has_many 对象“:ads”时,它返回“未定义的方法广告”异常。我在下面发布我的模型和 Controller 代码。请帮助我解决这个问题。
用户模型
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
广告 Controller
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
编辑
这是我的用户和广告迁移
用户迁移
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 => "")
我得到的错误..
最佳答案
您的User.searchID(query)
返回多个用户记录(关系对象),而不是单个用户记录。
如果将其更改为User.searchID(query).take
,它将仅获取一条记录,并且错误消失。
我不知道 session[:user_id]
包含什么值,但是查看您的 users
表,这只是一个整数 ID?在这种情况下,当前的方法就没有多大意义。我推荐这样的东西:
def create
@user = User.find(session[:user_id])
# Rest of create method
end
User.find
方法查找具有该确切 ID 的用户记录,并立即返回一条记录。这是使用 Ruby on Rails 获取记录的最常见方法之一。
关于ruby-on-rails - 将对象添加到一对多关系 ROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875447/