将对象添加到一对多关系ROR

时间:2015-04-26 08:34:26

标签: ruby-on-rails ruby

我无法将对象添加到关联类。 父类user与广告类具有has_many关系。 当我尝试从广告控制器访问用户的has_many对象“:ads”时,它会返回“未定义的方法广告”异常。我在下面发布我的模型和我的控制器代码。请帮我解决这个问题。

用户模型

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

修改

以下是我对用户和广告的迁移

用户迁移

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 => "")

我得到的错误..

enter image description here

2 个答案:

答案 0 :(得分:3)

您的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获取记录的最常用方法之一。

答案 1 :(得分:0)

我不确定@user = User.find(session[:user_id]) 的查询是否适合您,在postgres中它不会

HashMap

您不需要以上方法,您可以通过ID直接找到用户

public static void populateSynonymMap() {
    HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();

    String word = "bank";
    String synonymn[] = { "safe", "treasury", "credit union" };

    synonymMap.put(word, synonymn);

}