So, I'm really new to Ruby on Rails and the whole thing still sounds like Chinese to me. Excuse me if this is a stupid question, but I'm trying to make a new button on my app that lets me copy things.
On my form I have:
%span.btn.btn-mini.btn-inverse= link_to copy_image, copy_campaign_signal_processor_item_path(@campaign, @processor, item) ,data: { toggle:"modal",target: "#myModal"}, remote: true
That works fine and creates the button for me. Then, in routes.rb, I have:
resources :signal_processors, exclude: [:index, :new, :create], controller: 'processors' do
member do
get :modify, :action => :edit, :force_schema_update => true
end
resources :items do
member do
get :copy
end
end
Finally, in the items_controller.rb, I have:
def copy
@overlay_title = "Copy #{@processor.item_name}"
@processor.properties.each do |property|
unless @item.property_values.collect{|a| a.property_id}.index(property.id)
@item.property_values << SignalProcessor::PropertyValue.new(property: property)
end
end
respond_to do |format|
format.js
end
end
The problem is that for some reason item
doesn't seem to get passed to the copy
function in items_controller.rb, so every time I click the copy button, I get the error:
undefined method
property_values' for nil:NilClass`
for the line:
unless @item.property_values.collect{|a| a.property_id}.index(property.id)
What am I doing wrong? Why isn't item
getting passed?
@item
is an instance variable, and its value is nil
unless you set otherwise. It's what we have here - you don't set @item
anywhere in this action, which is why it's nil
. You should probably (assuming you have corresponding Item
model) type:
@item = Item.find(params[:id])
before you'd like to use @item
value.
First, you need to amend your form view to pass the Item
id, which you can use to look up the corresponding model object in your controller:
%span.btn.btn-mini.btn-inverse= link_to copy_image, copy_campaign_signal_processor_item_path(@campaign, @processor, item.id) ,data: { toggle:"modal",target: "#myModal"}, remote: true
In your form, you're passing three arguments to your path, but you haven't named them in your route yet. You can name the parameters you'll be passing to the copy
route within the :items
resource block:
resources :items do
member do
get 'copy/:campaign/:processor/:item_id', :action => 'copy'
end
end
Then, in your controller, you can look up your Item
by ID:
def copy
@item = Item.find(params[:item_id])
...
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.