This is getting printed in my views: #<Recipe:0x10536ff28> - ruby-on-rails

Why am I seeing an activerecord object IDs for each record coming out of my Recipe model in my recipes views? At the bottom of the index action I see this:
#<Recipe:0x1056c1d98>#<Recipe:0x1056c1cd0>
The model:
class Recipe < ActiveRecord::Base
attr_accessible :name, :description, :quick_facts, :ingredients, :instructions, :user_id, :hashtag, :image
mount_uploader :image, ImageUploader
end
The view:
.section-header The Recipes as seen on: #DriscollsMoments
= recipes.each do |recipe|
#recipe
#image-container
= link_to(image_tag(recipe.image_url, :width => 200, :height => 100, :border => 0), recipe_path(recipe.id))
#information
= link_to recipe.name, recipe_path(recipe.id), :class => 'recipe-name'
= link_to 'view recipe & tweet', recipe_path(recipe.id), :class => 'view-recipe'
.clear
%p= recipe.description
.clear
The Controller:
class RecipesController < ApplicationController
def index
#recipes = Recipe.find(:all)
end
def show
end
end
This problem is unique to this model - it's not doing it anywhere else in my app. I tried disabling carrierwave to see if that had any affect and it doesn't appear to make any difference. I have two recipes_controllers, one's an admin controller, but that shouldn't be the problem either. I know this is going to be obvious. Any ideas?

In your view, replace this:
= recipes.each do |recipe|
with this:
- recipes.each do |recipe|
The = causes the contents of the recipes array to be output after executing the loop.

I believe the line:
= recipes.each do |recipe|
should be:
- recipes.each do |recipe|

Related

Duplicating form field while editing nested form

I have two classes Food and food_category_price.
The association looks something like this:
has_many :food_category_prices, dependent: :destroy
accepts_nested_attributes_for :food_category_prices
The foods controller looks something like this for new, create and edit actions.
def new
#food = current_department.foods.new
#food.food_category_prices.build
end
def edit
#food = current_department.foods.find(params[:id])
end
def create
#food = current_department.foods.create(food_params)
if #food.persisted?
flash[:notice] = "Food was successfully created."
redirect_to foods_path
else
flash[:error] = "Error while adding food"
render :new
end
end
My food parameters looks something like this: (I have whitelisted the nested attributes' id)
def food_params
params.require(:food).permit(:name, :description, :price, :image ,food_category_prices_attributes: [:id,:category_id,:extra_price],:category_ids => [])
end
The nested form for new action of food is:
= form_for #food do |f|
.field.form-group
= f.file_field :image, class: 'd-none'
......
......
// Nested form from here
- current_department.categories.where(category_kind: 2).each do |category|
= f.fields_for :food_category_prices do |g|
= g.label :category_id, category.name + "("+String(category.price)+")"
= g.hidden_field :category_id, value: category.id
= g.label :extra_price, "Extra Price"
= g.number_field :extra_price
The problem:
The code words perfeclty fine while creating new food, and nested food_categoy_prices.
The problem is that, when i am editing the form, the attributes are duplicating. The labels such as extra price and category_id are duplicating.

Ruby on Rails error when validates_uniqueness_of using collection_select

First, sorry for my bad English. I'm still learning.
I have 3 tables in my DB:
Problem
has_many :registers
has_many :solutions, through : :registers
Solution
has_many :problems
has_many :problems, through : :registers
Register
belongs_to: problem
belongs_to :solution
The system is working well. I am able to insert new data in all of the 3 tables.
In the views for the table/model Register, to select problems and solutions, I make use of collection_select, like this:
= form_for #register do |f|
.field
= f.label :problem_id
= collection_select( :register, :problem_id, #problems, :id, :name, {}, { :multiple => false })
.field
= f.label :solution_id
= collection_select( :register, :solution_id, #courses, :id, :name, {}, { :multiple => false })
.field
= f.label :entry_at
= f.datetime_select :entry_at
.actions = f.submit
The problem only appears when I try to add this validation to Register:
validates_uniqueness_of :student_id , scope: :course_id
Then I get:
> undefined method `map' for nil:NilClass
> = collection_select( :register, :problem_id, #problems, :id, :name, {}, { :multiple => false })
And I dont know why.
So, I tried to do the validation by the controller:
def create
#register = Register.new(register_params)
problem_id = #register.problem_id
solution_id = #register.solution_id
if Register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
render 'new'
else
#register.save
respond_with(#register)
end
end
But the error remains.
I believe that the cause is the collection_select, but I don't know how to solve it.
Saying one more time, I am able to persist date in all the 3 DB tables. But when I try to avoid duplication, the error appears.
This is how I solve this problem:
def create
#register = register.new(register_params)
#if #register.save
# respond_with(#register)
#else
# #register = register.all
# render :new
#end
problem_id = #register.problem_id
solution_id = #register.solution_id
if register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
#register = register.new
#solutions = Solution.all
#problems = Problem.all
flash[:error] = "Problem alread in the register for this solution"
render 'new'
else
#register.save
respond_with(#register)
end
end

For each loop through API values

I'm having trouble finding the correct way to list out all of my data here is my setup. #product.pic_url will return 5 images but only shows the first one how would I iterate through them all?
product.rb
class TaobaoProduct
attr_reader :desc,
:approve_status,
:title,
:item_url,
:nick,
:num_iid,
:pict_url,
:pic_url,
:title,
:volume,
:zk_final_price,
:reserve_price,
:price,
:detail_url,
:cid
attr_writer :title
def initialize(product)
product.each { |name, value| instance_variable_set("##{name}", value) }
end
# function to get individual taobao product
# product_id: Taobao product id
def self.find(product_id)
tb_hash = OpenTaobao.get(
:method => 'taobao.item.get',
:fields => 'num_iid,title,nick,desc,pic_url',
:num_iid => product_id
)
new(tb_hash["item_get_response"]["item"])
end
end
product.haml
.container
.row
.col-xs-12
%h1= #product.title
.row
.product-v2.col-md-9
.row
.col-md-6.col-xs-12
%img{:src => "#{#product.pic_url}" + "_400x400.jpg"}
.col-md-6.col-xs-12
.price-v2
Assuming Product#pic_url actually returns an array of image urls, you could do something like this:
.container
.row
.col-xs-12
%h1= #product.title
.row
.product-v2.col-md-9
.row
.col-md-6.col-xs-12
- #product.pic_url.each do |url|
%img{:src => "#{url}_400x400.jpg"}
.col-md-6.col-xs-12
.price-v2

Can't display my category and subcategory in the views Rails 4

My website has Categories and subcategories,here is what i have in my seeds.rb,there i create a main category called "Video and animation",and 4 subcategories,than i assign the subcategories to the main category.
#category = Category.create!(name: "Video and animation")
["Intro", "Animation & 3D", "Editing and Post Production", "Other"].each do |name|
#subcategory = Subcategory.create!(name: name, category_id: #category.id)
end
It works well,in my rails console i see that everything works,the category_id for the added products changes to a number(integer as it should).
Question: How do i show the category in my views,so when someone clicks on that he gets all the products of that category.
And how do i show all the subcategories following the same principle.
Here is what i tried to put into my views
<% Category.all.each do |category| %>
<%= link_to category.name, gigs_path(category: category.name) %>
<% end %>
<% Subcategory.all.each do |subcategory| %>
<%= link_to subcategory.name, gigs_path(subcategory: subcategory.name) %>
<% end %>
The weird thing is that when i put in my product controller
this
def index
#category_id = Category.find_by(name: params[:category])
#gigs = Gig.where(category_id: #category_id).order("created_at DESC")
#subcategory_id = Subcategory.find_by(name: params[:subcategory])
#gigs = Gig.where(subcategory_id: #subcategory_id).order("created_at DESC")
end
It shows just the required subcategories,as i want,but the main category remains empty.
and if i put instead this into my controller
def index
#category_id = Category.find_by(name: params[:category])
#subcategory_id = Subcategory.find_by(name: params[:subcategory])
#gigs = Gig.where(category_id: #category_id).order("created_at DESC")
end
The main category works,as required,but the subcategories remain empty.
Note: In both cases,in the views,before anyone clicks on anything,i see the proper category and subcategories displayed.
Here is what i have in each of the 3 models
class Category < ActiveRecord::Base
has_many :subcategories
end
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end
class Product < ActiveRecord::Base
acts_as_votable
belongs_to :user
belongs_to :subcategory
has_attached_file :image, :styles => { :medium => "300x300>" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
Thank you for your time.
In controller action
#categories = Category.includes(:subcategories)
Add In views
<% #categories.each do |category| %>
<%= link_to category.name, gigs_path(category: category.name) %>
<% category.subcategories.each do |subcategory| %>
<%= link_to subcategory.name, gigs_path(subcategory: subcategory.name) %>
<% end %>
<% end %>
Change your index method in controller
def index
if params[:category]
c_id = Category.find(name: params[:category])
#gigs = Gig.where(category_id: c_id).order("created_at DESC")
elsif params[:subcategory]
subc_id = Subcategory.find(name: params[:subcategory])
#gigs = Gig.where(subcategory_id: subc_id).order("created_at DESC")
end
end

belongs_to add a relationship?

these are my models
class Apartment
belongs_to :house
end
class House
has_many :apartments
end
apartment_controller;
def index
#apartments = Appartment.all
end
apartment index view
.span9
#container
- #appartments.each do |apartment|
.item{:class => apartment.features_to_html_class }
%article.info.t_xs
.article-base
%section
.span3
%h2 #{link_to apartment.name, appartment_path(apartment)}
%p
= raw truncate(apartment.property_description, :length => 375, :omission => '...')
%footer
%ul.meta
%li.comments
#{apartment.count_ratings}
= t('apartment.details.reviews')
%li.notes
#{apartment.guests}
= t('apartment.details.persons')
%li.notes
#{apartment.bedrooms}
= t('apartment.details.bedrooms')
%li.notes
#{apartment.bathrooms}
= t('apartment.details.bathrooms')
%ul.thumbnails
%li.span5
= image_tag(apartment.attachments.last.file.url, :class => 'thumbnail')
- apartment.attachments.limit(4).each do |a|
%li.span1
%a{:href => "#"}
= image_tag(a.file.url(:thumb), :class => "thumbnail")
.span8
%footer
#more
#{link_to t('apartments.summary.button'), appartment_path(apartment), :class => 'btn btn-primary'}
i get all the apartments from the DB. But now i want to add a link (belongs_to) to the house in at the apartment summary. how can i do this...thanks..remco
Did you try
link_to 'House', house_path(apartment.house) ?
Try this:
<%= link_to 'House', house_path(apartment.house) %>
or
<%= link_to 'House', house_url(apartment.house) %>
Regards!
You got all the apartments in the database.
Now you run the sql to get the apartments object.
Then iterate each apartment and link it to house with the association.
This is done as follows:
def index
#apartments = Appartment.all
#apartments.each do |apartment|
#this is giving you the link to house via association defined.
apartment.house
#this is giving you the value of the field say `house_name` of house table that is linked to apartment.
#house_name = apartment.house.house_name
.
.
.
end
end

Resources