button_to не передает правильный идентификатор из хэша params - PullRequest
1 голос
/ 02 августа 2011

Button_to не передает правильный идентификатор line_item.В журнале ниже вы видите изменение bike_id с правильного '86' на неправильный '1' (который по совпадению является моим user_id).Любая помощь будет оценена.Ниже приведена ошибка из моего файла development.log, затем код из моего представления и контроллеров.Спасибо.

development.log

Started POST "/line_items?bike_id=86" for 127.0.0.1 at 2011-08-01 18:09:52 -0400

DEPRECATION WARNING: Setting filter_parameter_logging in ActionController is deprecated and has no longer effect, please set 'config.filter_parameters' in config/application.rb instead. (called from <class:ApplicationController> at /Users/willdennis/rails_projects/spinlister/app/controllers/application_controller.rb:8)

Processing by LineItemsController#create as HTML

Parameters: {"authenticity_token"=>"5GYQqvf7U5awhLrZ9Aw910ETf2kqOk3PI315jkjEfMU=", "bike_id"=>"86"}

[1m[35mCart Load (0.6ms)[0m SELECT "carts".* FROM "carts" WHERE ("carts"."id" = 8) LIMIT 1 [1m[36mBike Load (1.2ms)[0m [1mSELECT "bikes".* FROM "bikes" WHERE ("bikes"."id" = 86) ORDER BY bikes.created_at DESC LIMIT 1[0m [1m[35mSQL (0.5ms)[0m INSERT INTO "line_items" ("bike_id", "cart_id", "created_at", "updated_at") VALUES (1, 8, '2011-08-01 22:09:53.208978', '2011-08-01 22:09:53.208978') [1m[36mCart Load (1.5ms)[0m [1mSELECT "carts".* FROM "carts" WHERE ("carts"."id" = 8) LIMIT 1[0m Redirected to <a href="http://localhost:3000/carts/8" rel="nofollow">http://localhost:3000/carts/8</a> Completed 302 Found in 251ms

line_items_controller.rb

def create
 @cart = current_cart
 @bike = Bike.find(params[:bike_id])
 @line_item = @cart.line_items.build(:bike_id => @bike)
 respond_to do |format|
    if @line_item.save
      format.html { redirect_to(@line_item.cart,
      :notice => 'Line item was successfully created.') }
      format.xml { render :xml => @line_item,
      :status => :created, :location => @line_item }
    else
      format.html { render :action => "new" }
      format.xml { render :xml => @line_item.errors,
      :status => :unprocessable_entity }
    end
  end
end

просмотров / байков / шоу

<%= button_to "Rent this Bicycle!", line_items_path(:bike_id => @bike), {:id => "rentthisbike"} %>

bike.rb

class Bike < ActiveRecord::Base
 belongs_to :user
 has_many :line_items
 attr_accessible :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood, :bike_id
end

line_item.rb

class LineItem < ActiveRecord::Base
  belongs_to :bike
  belongs_to :cart

  accepts_nested_attributes_for :bike, :cart

  attr_accessible :bike_id, :bike, :cart, :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood 

end

cart.rb

class Cart < ActiveRecord::Base
 has_many :line_items, :dependent => :destroy
 belongs_to :user

 accepts_nested_attributes_for :line_items

 attr_accessible :bike_id, :line_items, :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood 
end

1 Ответ

1 голос
/ 02 августа 2011

Можете ли вы попробовать этот код и опубликовать запись @@@@ атрибутов позиции из файла журнала вместе с хэшем params Я думаю, что это может быть связано с вашим методом current_cart, но я не уверен

line_items_controller.rb

def create
 @bike = Bike.find(params[:bike_id])
 @line_item = current_cart.line_items.build
 @line_item.bike = @bike
 logger.debug("@@@@ Line item attributes = #{@line_item.inspect}")
 respond_to do |format|
    if @line_item.save
      format.html { redirect_to(@line_item.cart,
      :notice => 'Line item was successfully created.') }
      format.xml { render :xml => @line_item,
      :status => :created, :location => @line_item }
    else
      format.html { render :action => "new" }
      format.xml { render :xml => @line_item.errors,
      :status => :unprocessable_entity }
    end
  end
end

Обновление.

Ваш предыдущий код был в порядке, за исключением этой строки @line_item = @ cart.line_items.build (: bike_id => @bike) Вы указали весь класс в качестве значения идентификатора велосипеда вместо идентификатора велосипеда. Я знаю, что это не согласуется с передачей параметров формы, но это так.

...