I’m trying to pick up the shop_id and subscription_id from a cart and insert/save them into the purchase database.
I have a cart, line_items and subscriptions.
And this is how I’m trying to do this:
#purchase = #cart.line_items.build
#purchase = current_shop.purchases.build(purchase_params)
#purchase.save!
I got the shop_id, but the subscription_id for some reason is nil.
Any ideas what maybe wrong?
Update 1
def purchase_params
params.permit(:subscription_id, :shop_id, :created_at, :updated_at, :id, :cart_id)
end
Started POST "/line_items?subscription_id=1" for ::1 at 2017-06-18 16:45:12 +0300
Processing by LineItemsController#create as HTML
Parameters: {"authenticity_token"=>"dUonc4AnCvFTuK1b+TAKho/kmpvl7XaOM7SGcNalzdQV1+CqhY4 p7znDiL/TV12pVKeDTqlR7j5NL65X1S/75A==", "subscription_id"=>"1"}
Cart Load (0.1ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT ? [["id", 14], ["LIMIT", 1]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "carts" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2017-06-18 13:45:12 UTC], ["updated_at", 2017-06-18 13:45:12 UTC]]
(0.7ms) commit transaction
Subscription Load (0.2ms) SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "line_items" ("subscription_id", "cart_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["subscription_id", 1], ["cart_id", 18], ["created_at", 2017-06-18 13:45:12 UTC], ["updated_at", 2017-06-18 13:45:12 UTC]]
(0.9ms) commit transaction
Redirected to http://localhost:3000/carts/18
Completed 302 Found in 21ms (ActiveRecord: 3.2ms)
I'm implementing braintree payments via the following create method and this is where I have the small peace of code:
def create
current_shop.has_payment_info?
#result = Braintree::Transaction.sale(
amount: #cart.total_price,
payment_method_nonce: params[:payment_method_nonce],
customer: {
first_name: current_shop.first_name,
last_name: current_shop.last_name,
company: current_shop.shop_name,
email: current_shop.email,
phone: current_shop.phone_number,
website: current_shop.web_page
},
options: { store_in_vault: true })
if #result.success?
current_shop.update(braintree_customer_id: #result.transaction.customer_details.id) unless current_shop.has_payment_info?
#purchase = #cart.line_items.build
#purchase.save!
#purchase = current_shop.purchases.build(purchase_params)
#purchase.save!
#cart.destroy
redirect_to front_index_path, notice: 'Your transaction was succesfully processed'
else
gon.client_token = generate_client_token
redirect_to :back, :notice => 'Something went wrong while processing your transaction. Please try again!'
end
end
Update 2
class Purchase < ApplicationRecord
belongs_to :shop
belongs_to :cart
end
class Shop < ApplicationRecord
has_many :items
has_many :purchases
has_many :subscriptions
end
class Subscription < ApplicationRecord
has_many :line_items
belongs_to :shop
end
class Cart < ApplicationRecord
has_many :line_items, dependent: :destroy
has_many :purchases
end
class LineItem < ApplicationRecord
belongs_to :subscription
belongs_to :cart
end
Build here only links up a new line_item with #cart, like this, LineItem.new(cart_id: #cart.id). subscription_id is not linked here as #cart doesn't have a relationship with subscriptions.
#cart.line_items.build
line_item = #cart.line_items.build
fetch the desired subscription_id and assign it to 'line_item.subscription_id '
line_item.subscription_id = fetch_the_subscription_id
line_item.save!
Related
i am building an eCommerce app in rails which has two products Chairs and Bookcabinets, i have created two different controllers and models for chairs and bookcabinets, it all worked now i wanted the user to be able to add these products to a cart so i created a ordering system from scratch by watching a tutorial, it worked for chairs but when i add bookcabinets to shopping_cart model it gives me an error: Couldn't find Chair with 'id'=
Server Log
Started POST "/cart/items" for 127.0.0.1 at 2018-09-26 14:16:43 +0530
(0.7ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wGAl7gZGXipKt7EzzZT1LuBgn2k8KnlaPagp0cQ3l6pIkr6mx8MdJAuhgkY7EEttrHjTSSpcRjqe0qZ0a2hrAA==", "bookcabinet_id"=>"1", "quantity"=>"40"}
Chair Load (0.8ms) SELECT "chairs".* FROM "chairs" WHERE "chairs"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 106ms (ActiveRecord: 3.8ms)
ActiveRecord::RecordNotFound (Couldn't find Chair with 'id'=):
app/models/shopping_cart.rb:20:in `add_item'
app/controllers/order_items_controller.rb:8:in `create'
My Order_items_controller
class OrderItemsController < ApplicationController
def index
#items = current_cart.order.items
end
def create
current_cart.add_item(
chair_id: params[:chair_id],
bookcabinet_id: params[:bookcabinet_id],
quantity: params[:quantity]
)
redirect_to cart_path
end
def destroy
current_cart.remove_item(id: params[:id])
redirect_to cart_path
end
end
My Order_controller
class OrdersController < ApplicationController
def new
#order = current_cart.order
end
end
** My Order model**
class Order < ApplicationRecord
has_many :items, class_name: 'OrderItem'
end
My Order_item Model
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :chair
belongs_to :bookcabinet
end
My Shopping_Cart Model
class ShoppingCart
delegate :sub_total, to: :order
def initialize(token:)
#token = token
end
def order
#order ||= Order.find_or_create_by(token: #token) do |order|
order.sub_total = 0
end
end
def items_count
order.items.sum(:quantity)
end
def add_item(chair_id:, bookcabinet_id:, quantity: 1)
chair = Chair.find(chair_id),
bookcabinet = Bookcabinet.find(bookcabinet_id)
order_item = order.items.find_or_initialize_by(
chair_id: chair_id,
bookcabinet_id: bookcabinet_id
)
order_item.price = chair.price
order_item.price = bookcabinet.price
order_item.quantity = quantity
ActiveRecord::Base.transaction do
order_item.save
update_sub_total!
end
end
def remove_item(id:)
ActiveRecord::Base.transaction do
order.items.destroy(id)
update_sub_total!
end
end
private
def update_sub_total!
order.sub_total = order.items.sum('quantity*price')
order.save
end
end
My Create_order migration
class CreateOrders < ActiveRecord::Migration[5.1]
def change
create_table :orders do |t|
t.string :first_name
t.string :last_name, null: false
t.decimal :sub_total, precision: 15, scale: 2, null: false
t.timestamps
end
end
end
my CreateOrderItems migration
class CreateOrderItems < ActiveRecord::Migration[5.1]
def change
create_table :order_items do |t|
t.belongs_to :order, null: false
t.belongs_to :chair, null: false
t.belongs_to :bookcabinet
t.integer :quantity, null: false
t.decimal :price, precision: 15, scale: 2, null: false
t.timestamps
end
end
end
Routes
get '/cart', to: 'order_items#index'
resources :order_items, path: '/cart/items'
get '/cart/checkout', to: 'orders#new', as: :checkout
patch '/cart/checkout', to: 'orders#create'
Add To Cart Form
<div class="button my-2">
<%= form_tag order_items_path do %>
<%= hidden_field_tag :bookcabinet_id, #bookcabinet.id %>
<%= number_field_tag :quantity, 1 %>
<button type="submit" class="btn cart"><i class="d-inline fa fa-cart-arrow-down" aria-hidden="true"></i><p class="d-inline">Add To Cart</p></button>
<% end %>
Updated Server Log
Started POST "/cart/items" for 127.0.0.1 at 2018-09-27 00:24:13 +0530
(0.6ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gqwsV8Z/0p74Y8WPLMmfk9vmoSPCFpP+lAtVxxH3KSvWUzYYIFtbQRkAzM5yh5HS/wAzelr90LJW64joFUpGwg==", "bookcabinet_id"=>"1", "quantity"=>"40"}
Bookcabinet Load (0.7ms) SELECT "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Order Load (0.9ms) SELECT "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ? [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
OrderItem Load (0.5ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? AND "order_items"."chair_id" IS NULL AND "order_items"."bookcabinet_id" = ? LIMIT ? [["order_id", 4], ["bookcabinet_id", 1], ["LIMIT", 1]]
(0.2ms) begin transaction
Bookcabinet Load (0.3ms) SELECT "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.4ms) SELECT SUM(quantity*price) FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
(0.2ms) commit transaction
Redirected to http://localhost:3000/cart
Completed 302 Found in 557ms (ActiveRecord: 10.4ms)
Started GET "/cart" for 127.0.0.1 at 2018-09-27 00:24:14 +0530
Processing by OrderItemsController#index as HTML
Order Load (0.5ms) SELECT "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ? [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
Rendering order_items/index.html.erb within layouts/application
(0.4ms) SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
OrderItem Load (1.1ms) SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
Rendered order_items/index.html.erb within layouts/application (15.0ms)
CACHE (0.1ms) SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ? [["order_id", 4]]
Rendered layouts/_header.html.erb (22.0ms)
Rendered layouts/_footer.html.erb (1.9ms)
Completed 200 OK in 1313ms (Views: 1304.9ms | ActiveRecord: 2.1ms)
You are searching for chair item every time you call add_item method so its throwing an error as you are not passing chair id so you need to modify the method as below
def add_item(chair_id:, bookcabinet_id:, quantity: 1)
chair = Chair.find(chair_id) if chair_id
bookcabinet = Bookcabinet.find(bookcabinet_id) if bookcabinet_id
order_item = order.items.find_or_initialize_by(
chair_id: chair_id,
bookcabinet_id: bookcabinet_id
)
order_item.price = chair.price if chair
order_item.price = bookcabinet.price
order_item.quantity = quantity
ActiveRecord::Base.transaction do
order_item.save
update_sub_total!
end
end
Please feel free to ask if there are any questions regarding the same
I'm working on an app where I have two Tables that have a many-to-many relationship, joined in the middle by a join table.
Stadium model:
class Stadium < ActiveRecord::Base
has_many :stadiumteams
has_many :teams, :through => :stadiumteams
Team model:
class Team < ActiveRecord::Base
has_many :stadiumteams
has_many :stadiums, :through => :stadiumteams
end
StadiumTeam model (the jointable):
class StadiumTeam < ActiveRecord::Base
belongs_to :stadium
belongs_to :team
end
When I create a new Stadium I want to be able to select one or multiple teams that are associated with a stadium and save the relationship to the join-table (stadiumteams).
Here's the create action form the Stadiums Controller.
def create
#stadium = current_user.stadiums.build(stadium_params)
respond_to do |format|
if #stadium.save
teams = Team.where(:id => params[:team])
teams.each {|team| #stadium.teams << team}
format.html { redirect_to #stadium, notice: 'Stadium was successfully created.' }
format.json { render :show, status: :created, location: #stadium }
else
format.html { render :new }
format.json { render json: #stadium.errors, status: :unprocessable_entity }
end
end
end
When I try to create a new Stadium I get this output from the terminal.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"m+HAw4LRPmozIkigzuB/SFdcAFPTL735n6FyavH0SwjGXl7NHCLmDCXMTvx8bVixz+sL7tfn1zzCl04Q+w6Pdw==", "stadium"=>{"name"=>"Friends Arena", "capacity"=>"100000", "surface"=>"", "official_opening_date(1i)"=>"2017", "official_opening_date(2i)"=>"12", "official_opening_date(3i)"=>"4", "cost"=>"10000", "web_url"=>"teststadium.com", "record_attendance"=>"999790", "city"=>"", "country"=>"", "location_name"=>"", "longitude"=>"", "latitude"=>"", "address"=>"Friends Arena, Solna, Sweden"}, "team_id"=>"3", "commit"=>"Create Stadium"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.2ms) begin transaction
SQL (0.5ms) INSERT INTO "stadiums" ("name", "capacity", "city", "country", "location_name", "address", "surface", "cost", "web_url", "record_attendance", "official_opening_date", "user_id", "latitude", "longitude", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["name", "Friends Arena"], ["capacity", 100000], ["city", "Solna"], ["country", "Sweden"], ["location_name", ""], ["address", "Friends Arena, Solna, Sweden"], ["surface", ""], ["cost", 10000.0], ["web_url", "teststadium.com"], ["record_attendance", 999790], ["official_opening_date", "2017-12-04"], ["user_id", 1], ["latitude", 59.3727005], ["longitude", 18.0002317], ["created_at", "2017-12-04 13:18:45.841931"], ["updated_at", "2017-12-04 13:18:45.841931"]]
(2.8ms) commit transaction
It seems like "team_id"=>"3"" is added as a parameter but it's not inserted into any table. And I can't output the relationship between Stadiums and Teams in any way right now.
What I want to accomplish is to be able to show all Teams that are associated with Stadium on the Stadium show page. And all Stadiums that are associated with a Team on the teams Show page.
Any help or guidance would be very appreciated!
EDIT:
Stadium params:
def stadium_params
params.require(:stadium).permit(:name, :capacity, :city, :country, :location_name, :address, :longitude, :latitude, :image, :surface, :official_opening_date, :cost, :web_url, :also_known_as, :record_attendance)
end
EDIT2: SOLVED:
After struggling with this. I finally found a solution: has_many :through uninitialized constant
I simply added :class_name => 'StadiumTeam' to the team and stadium model and it worked!
I finally found a solution to this.
I simply added :class_name => 'StadiumTeam' to the team and stadium model and it worked!
More info here:
has_many :through uninitialized constant
I'm new to rails and I want to know how to fetch a one-to-one relationship. I want to fetch users city. In my postgresql database I have:
cities Table:
city:varchar
zipcode: integer
users Table
name:varchar
city_id:int
and in city and user model I have:
class City < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :city
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
I tried the following in my search controller but didnt work, when logged in:
current_user.city
I get the following error
Processing by SearchController#index as HTML
Parameters: {"utf8"=>"✓", "q"=>"", "criteria"=>"1", "commit"=>"Search"}
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1
PG::UndefinedColumn: ERROR: column cities.user_id does not exist
LINE 1: SELECT "cities".* FROM "cities" WHERE "cities"."user_id" =...
^
: SELECT "cities".* FROM "cities" WHERE "cities"."user_id" = $1 LIMIT 1
Completed 500 Internal Server Error in 11ms
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column cities.user_id does not exist
LINE 1: SELECT "cities".* FROM "cities" WHERE "cities"."user_id" =...
^
: SELECT "cities".* FROM "cities" WHERE "cities"."user_id" = $1 LIMIT 1):
why am I suppose to add a user_id column to cities table, when I have cities foreign key in users table? I dont want to add user_id into cities table.
You can use has_one :through association with join table. Some example for you below.
user model:
class User < ActiveRecord::Base
has_one :city, through: :user_city
has_one :user_city
end
city model:
class City < ActiveRecord::Base
belongs_to :user
end
user city join model:
class UserCity < ActiveRecord::Base
belongs_to :city
belongs_to :user
end
migration for join tables:
class JoinUserCity < ActiveRecord::Migration
def change
create_table :user_cities do |t|
t.integer :user_id
t.integer :city_id
end
end
end
Test in rails console:
=> u = User.create
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-12-07 15:47:14.595728"], ["updated_at", "2014-12-07 15:47:14.595728"]]
(3.3ms) commit transaction
=> #<User id: 4, created_at: "2014-12-07 15:47:14", updated_at: "2014-12-07 15:47:14">
=> u.city
City Load (0.2ms) SELECT "cities".* FROM "cities" INNER JOIN "user_cities" ON "cities"."id" = "user_cities"."city_id" WHERE "user_cities"."user_id" = ? LIMIT 1 [["user_id", 4]]
=> nil
=> c = City.create
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "cities" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-12-07 15:47:24.535039"], ["updated_at", "2014-12-07 15:47:24.535039"]]
(3.3ms) commit transaction
=> #<City id: 1, created_at: "2014-12-07 15:47:24", updated_at: "2014-12-07 15:47:24">
irb(main):004:0> u.city = c
UserCity Load (0.3ms) SELECT "user_cities".* FROM "user_cities" WHERE "user_cities"."user_id" = ? LIMIT 1 [["user_id", 4]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "user_cities" ("city_id", "user_id") VALUES (?, ?) [["city_id", 1], ["user_id", 4]]
(1.0ms) commit transaction
=> #<City id: 1, created_at: "2014-12-07 15:47:24", updated_at: "2014-12-07 15:47:24">
irb(main):005:0> u.save
(0.1ms) begin transaction
(0.1ms) commit transaction
=> true
=> u = User.last
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
=> #<User id: 4, created_at: "2014-12-07 15:47:14", updated_at: "2014-12-07 15:47:14">
=> u.city
City Load (0.2ms) SELECT "cities".* FROM "cities" INNER JOIN "user_cities" ON "cities"."id" = "user_cities"."city_id" WHERE "user_cities"."user_id" = ? LIMIT 1 [["user_id", 4]]
=> #<City id: 1, created_at: "2014-12-07 15:47:24", updated_at: "2014-12-07 15:47:24">
take a look at the document of has_one and belogns_to,
belongs_to(name, options = {})
Specifies a one-to-one association with another class. This method should only be used if this class
contains the foreign key. If the other class contains the foreign key, then you should use has_one
instead.
as the user table has the foreign key, you should change your model definition like this
class City < ActiveRecord::Base
has_one :user
end
class User < ActiveRecord::Base
belongs_to :city
end
I have 2 models: User and Collective, along with their join table, Membership. When a user creates a new collective, I want to simultaneously create a new membership between the two. Right now I have my create function partially working, in that the collective 'new' form adds a collective record to my db but no membership record is added.
User Model
class User < ActiveRecord::Base
has_many :collectives, :through => :memberships
has_many :memberships
end
Collective Model
class Collective < ActiveRecord::Base
has_many :users, :through => :memberships
has_many :memberships
end
Membership Model
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :collective
validates :user_id, presence: true
validates :collective_id, presence: true
end
Collective Controller
def new
#collective = Collective.new if user_signed_in?
end
def create
#collective = Collective.new(collective_params)
if #collective.save
current_user.memberships.create(collective_id: #collective)
flash[:success] = "Collective created!"
redirect_to collective_url(#collective)
else
render 'new'
end
end
private
def collective_params
params.require(:collective).permit(:name, :description, :location, :num_of_users, :num_of_projects)
end
end
Log
Started POST "/collectives" for 127.0.0.1 at 2014-11-06 10:49:39 -0500
Processing by CollectivesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Dh/rG1N6ulrJSIiEaAgudnaltjxnKwCw5sdUQxG9qnE=", "collective"=>{"name"=>"Honda Civic", "location"=>"Cars", "description"=>"Blaahhhhh"}, "commit"=>"Create Collective"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "collectives" ("created_at", "description", "location", "name", "num_of_projects", "num_of_users", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", "2014-11-06 15:49:40.003338"], ["description", "Blaahhhhh"], ["location", "Cars"], ["name", "Honda Civic"], ["num_of_projects", 0], ["num_of_users", 1], ["updated_at", "2014-11-06 15:49:40.003338"]]
(145.3ms) commit transaction
(0.0ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/collectives/7
Completed 302 Found in 208ms (ActiveRecord: 146.7ms)
It seems like the line current_user.memberships.create(collective_id: #collective) is just being ignored for some reason given that the redirect happens fine. Help would be much appreciated. Thanks in advance!
I would say the problem is with passing instance object instead of id. It should be:
if #collective.save
current_user.memberships.create(collective_id: #collective.id)
flash[:success] = "Collective created!"
redirect_to collective_url(#collective)
else
render 'new'
end
Since create method only returns true/false (false in this case because of validation) and does not raise any exception, it gets redirected into show action.
I am trying to create a relation_level, with a score attribute, for each interest_question/feed pair. I am doing this with an accepts_nested_attributes_for :relation_levels in the feed form. Everything renders as it should, and when the form is submitted, a feed is created, but no relation_levels are created.
I've also tried adding the feed_id as a hidden field in the form.
(using rails 4 and haml)
app/models/interest_question.rb
class InterestQuestion < ActiveRecord::Base
has_many :relation_levels, dependent: :destroy
has_many :interest_answers, dependent: :destroy
end
app/models/relation_level.rb
class RelationLevel < ActiveRecord::Base
belongs_to :feed
belongs_to :interest_question
end
app/models/feed.rb
class Feed < ActiveRecord::Base
has_many :relation_levels, dependent: :destroy
has_many :interest_questions, through: :relation_levels
accepts_nested_attributes_for :relation_levels
end
app/views/feeds/_form.html.haml
=form_for(#feed) do |f|
...other fields
...other fields
-#interest_questions.each do |iq|
=f.fields_for #feed.relation_levels.build(interest_question_id: iq.id) do |rl|
=rl.label iq.question_text
=rl.range_field :score, max: 100, min: 0, default: 0
=f.submit
app/controllers/feeds_controller.rb
class FeedsController < ApplicationController
def new
#feed = Feed.new
#sources = Source.all
#interest_questions = InterestQuestion.all
end
def create
#feed = Feed.new(feed_params)
if #feed.save
redirect_to '/feeds', notice: 'Feed created.'
else
render action: 'new'
end
end
...
private
def feed_params
params.require(:feed).permit(..., relation_levels_attributes:
[:interest_question_id, :score, :feed_id])
end
Server output:
Started POST "/feeds" for 127.0.0.1 at 2013-12-30 15:00:58 -0600
Processing by FeedsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/+TOOdpZZk85YvVlxkRIpLNfPfVVtGUTlKPb9Ctkvh8=", "feed"=>{"url"=>"lkas6df.com", "source_id"=>"1", "section"=>"kasl6d6fa", "area_importance"=>"", "is_local_news"=>"0", "relation_level"=>{"score"=>"17"}}, "commit"=>"Create Feed"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = '6fcabf7c7b1376250b1ffa589ff4f2279854d066' LIMIT 1
Unpermitted parameters: relation_level
(0.1ms) begin transaction
Source Load (0.1ms) SELECT "sources".* FROM "sources" WHERE "sources"."id" = ? ORDER BY "sources"."id" ASC LIMIT 1 [["id", 1]]
Feed Exists (0.2ms) SELECT 1 AS one FROM "feeds" WHERE "feeds"."url" = 'lkas6df.com' LIMIT 1
SQL (1.7ms) INSERT INTO "feeds" ("created_at", "section", "source_id", "updated_at", "url") VALUES (?, ?, ?, ?, ?) [["created_at", Mon, 30 Dec 2013 21:00:58 UTC +00:00], ["section", "kasl6d6fa"], ["source_id", 1], ["updated_at", Mon, 30 Dec 2013 21:00:58 UTC +00:00], ["url", "lkas6df.com"]]
(170.8ms) commit transaction
Redirected to http://localhost:3000/feeds
I've been stuck on this for a while, thanks in advance for any help :)
This should be a comment, but it's too big:
Maybe this could be your issue?
=f.fields_for #feed.relation_levels.build(interest_question_id: iq.id) do |rl|
This builds an ActiveRecord object on the fly, which IMO is bad practice. I'd build the object in the controller, and then call the object in the f.fields_for, like this:
#app/controllers/feeds_controller.rb
def new
#feed = Feed.new
#sources = Source.all
#interest_questions = InterestQuestion.all
#interest_questions.count.times do
#feed.relation_levels.build
end
end
You can then call:
=f.fields_for :relation_levels do |rl|
Much cleaner, and will likely help with your debugging!