简体   繁体   中英

Rails Relationships, Create New Model on has_many_through

I have three models: A 'user', which has multiple 'manufacturers', which each have multiple 'categories.' I want to be able to run searches for a user's categories through manufacturers, and there would be multiples of the latter two for each user - a user could have 5 or 6 manufacturers, each of which would have 5-6 categories. I got the manufacturers associated to the users okay, but now I'm trying to create the categories through the scaffold form and I can't make it so it pulls the manufacturer_id into the form the way I did with manufacturers and users. I know it's just a param thing I'm missing, but I've never done a has_many_through association before.

user.rb

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 :manufacturers
  has_many :categories, through: :manufacturers
end

manufacturer.rb

class Manufacturer < ActiveRecord::Base
  belongs_to :user
  has_many :categories
end

category.rb

class Category < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :user
end

For the create in my manufacturer's controller, I just did:

@manufacturer = current_user.manufacturers.build(manufacturer_params)

But I've tried doing something similar in the create of my category and it's not pulling the id of the manufacturer for the category. What would the create function of this one look like? It'd be the create function for category, which is tied to manufacturers, which is tied to users.

@category = current_user.categories.new(category_params)
if @category.save
    #do stuff
end

Using the new method will give you your user_id and saving it will give it it's id (after successfully saving).

It looks like you're just trying to create another nested object. If that is the case, you need to find both of the parent objects first.

def create
  @user = current_user
  @manufacturer = @user.manufacturers.find(params[:manufacturer_id])
  @category = @manufacturer.categories.build(category_params)
  #if save...####
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM