简体   繁体   中英

How to create a new joined table record without creating a new instance of either record. Rails

I have a three tables: User , fruits , user_fruits

There are set number of users and fruits in the world. I cannot create duplicate fruits. Say the fruits already exist in the database, and I want to use them, so I'm not creating new fruits.

Assume we're in a controller and all I want to do is create a new instance of user_fruits . I also want to delete the joined table instance in the destroy action but not the actual fruit itself. Is this the way to do it?

def create
   user.user_fruits.create!(fruit: fruit)
end

def destroy
   user.user_fruits.find_by(fruit: fruit).destroy!
end


private

attr_reader :fruit

def load_fruit
@fruit = Fruit.find_by(color: red, sweetness: 100)
end

I also want my destroy and create to raise an error if it fails.

If you just want to create a new instance then you can simply use new or build

def create
  @new_fruit = user.fruits.new # or fruits.build
end

Update

New instance of user_fruits ? Then you should try something like..

user.user_fruits.new

def create
  user.user_fruits.create!(fruit_id: @fruit.id)
end

def destroy
 user.user_fruits.find_by_fruit_id(@fruit.id).destroy!
end

And if you want to use reader anyway then replace @fruit with fruit

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