jeudi 31 janvier 2019

Rails: create and destroy belongs_to association through link_to actions

I am working on an admin interface where I have images and heroes. The hero table consists in only two columns: id and image_id. I would like to be able to add and remove images to the hero table.

I have a select_to_hero and select_from hero action and view which display either all images not already connected or all existing heroes and both work, but the add_to_hero and remove_from_hero actions, which I use to create a new or destroy an existing association do not work.

Hero.rb Model

class Hero < ActiveRecord::Base
  attr_accessible :image_id
  belongs_to :image
end

Image.rb Model

class Image < ActiveRecord::Base
  attr_accessible :alt, :author, :copyright, :file_name, :title
  has_one :hero
  mount_uploader :file_name, ImageUploader
end

Select_from_hero.html.erb

<% @heroes.each do |hero| %>
  <%= link_to(image_tag(hero.image.file_name.url(:thumb), {:action => 'remove_from_hero', :id => hero}) %>
<% end %>

Select_to_hero.html.erb

<% @images.each do |image| %>
  <%= link_to(image_tag(image.file_name.url(:thumb), {:action => 'add_to_hero', :id => image}) %>
<% end %>

images_controller.rb

def add_to_hero
  @hero.image << Image.find(params[:id]) unless @hero.image.include?(Image.find(params[:id]))
  if @hero.save
    ..
  else
    render :action => 'select_to_hero'
  end
end

def remove_from_hero
  @hero.image.delete(Image.find(params[:id]))
  if @hero.save
    ..
  else
    render :action => 'select_from_hero'
  end
end

With this setting I get:

NoMethodError in Admin::ImagesController#add_to_hero
undefined method `image' for nil:NilClass

and

NoMethodError in Admin::ImagesController#remove_from_hero
undefined method `image' for nil:NilClass

But I can query an existing association:

> Hero.find(2).image
  Hero Load (0.3ms)  SELECT `heroes`.* FROM `heroes` WHERE `heroes`.`id` = ? LIMIT 1  [["id", 2]]
  Image Load (0.3ms)  SELECT `images`.* FROM `images` WHERE `images`.`id` = 1 LIMIT 1
 => #<Image id: 1, file_name: "red.jpg", title: "blu", alt: "yellow", author: "John", copyright: "Jane", created_at: "2019-01-29 19:50:25", updated_at: "2019-01-29 19:50:25"> 

How can I get this working?

Aucun commentaire:

Enregistrer un commentaire