I am currently developing a somewhat 'big' project. In this project I have many models, views, and controllers from which I have to mention the following:
Group.rb:
class Group < ActiveRecord::Base
has_many :users, through: :grouprel
has_many :grouprel, dependent: :destroy
validates :name, presence: true, length: {maximum: 25},
uniqueness: { case_sensitive: false }
validates :description, presence: true , length: {maximum: 140}
end
Grouprel.rb
class Grouprel < ActiveRecord::Base
belongs_to :user
belongs_to :group
validates :user_id, presence: true
validates :group_id, presence: true
end
User.rb
class User < ActiveRecord::Base
.....
has_many :groups, through: :grouprel, dependent: :destroy
has_many :grouprel, dependent: :destroy
.....
StaticPageController:
class StaticPagesController < ApplicationController
def home
if logged_in?
#tweet = current_user.tweets.build
#feed_items = current_user.feed.paginate(page: params[:page])
#groupi = Grouprel.where(user_id: current_user.id).pluck(:group_id)
#groupies = Group.where(id: #groupi).paginate(page: params[:page])
end
end
.....
end
Home.html.erb:
<% if logged_in? %>
.......
<section class="user_info">
<%= render 'shared/group_participation' %>
</section>
</aside>
.............
_group_participation.html.erb
<h5> Your groups: </h5>
<% if #groupies %>
<ol class="tweets">
<%= content_tag_for(:li, #groupies) do %>
<%= link_to #groupies.name, group_path(#groupies) %>
<% end %>
</ol>
<%= will_paginate #groupies %>
<% end %>
here I want to display every single group that a user is part of. The error I get when trying to get the #groupies in the StaticPagesController is %23<Group::ActiveRecord_Relation:0x007f86b00f6ed0> . I checked in my rails console , and it should return something.
What my limited knowledge about rails and ruby can tell is that this is a problem because the StaticPageController can't see the Grouprel.rb table. I tried to include controllers in herlpers. I even tried to define a method that returns 'groupies' in the application controller and then use that in the StaticPagesController. Could I get a hint of why I get that error returned ?
If my post has to contain any more specifications please do tell I will post them the second I see the request
You're not iterating over the groupies collection and are calling the name method on the collection itself. content_tag_for can iterate over the collection for you but you need to use the value it yields to the block:
<%= content_tag_for(:li, #groupies) do |group| %>
<%= link_to group.name, group_path(group) %>
<% end %>
Related
I somehow broke my application and can't seem to find my mistake and would appreciate some help a lot.
<%= debug #relquotes %>
<%= debug #book%>
<h4 class="text-center">Related Quotes</h4>
<% #relquotes.each do |quote| %>
<article class="blog-1 blog-archive py-5">
<div class="col-12 col-md-8 mr-md-auto ml-md-auto">
<ol class="list-unstyled">
<li>
<h2 class="leading-normal mb-3"><%= quote.title %></h2>
<div class="article-meta color-grey-50">
<div class="media-body d-flex align-items-center">
<p class="m-0 media-heading"><a>by </a><%= link_to quote.user.username, user_path(quote.user) %> •
created <%= time_ago_in_words(quote.created_at) %> ago</p>
</div>
</div>
<p class="quotebody"><%= sanitize quote.body.first(240) %> (...)</p>
<a> <%= link_to quote do %> Read more →</a>
<% end %>
</ol>
</div>
</article>
<% end %>
Got this on my Book view and I have related quotes from books that I want to display with this
class Quote < ApplicationRecord
belongs_to :user
belongs_to :category
belongs_to :book
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true, length: {minimum: 240}
end
class Book < ApplicationRecord
belongs_to :user, optional: true
belongs_to :category, optional: true
has_many :quotes
has_many :reviews, dependent: :destroy
has_attached_file :book_cover, styles: {book_index: '250x350>', book_show: '325x475>'}
validates_attachment_content_type :book_cover, content_type: /\Aimage\/.*\z/
end
My books controller
class BooksController < ApplicationController
layout "_app_nav"
before_action :set_book, only: [:show, :edit, :update, :destroy]
# GET /books/1
def show
#average_review = if #book.reviews.blank?
0
else
#book.reviews.average(:rating).round(2)
end
#relquotes = #book.quotes
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
#book = Book.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def book_params
params.require(:book).permit(:title, :author, :description, :user_id, :book_cover, :category_id)
end
end
The debug #book works fine and my book gets displayed. I confirmed via rails console that the quote is associated with the book.
The debug #relquotes resolves in plain '--- []'.
It was working before and I cant seem to find where I messed it up.
My #relquotes should display all the quotes that are associated with a book. I can confirm that quotes are associated with a book.
eg. quote has book_id = 1 - therefore the book with the book_id 1 should display this quote as a 'related quote'.
Any help would be appreciated.
Thanks in advance!
I'm writing a simple time tracking app where the user has_many clients and where the client has_many projects.
I want a user to be able to view a list of their projects (for all clients). To implement this, I've set up a has_many, through relationship between the users and projects.
But for some reason I can't get the projects to show up in their index view. There's probably a really simple reason for this that I'm just not noticing, so apologies upfront if that's the case.
Here's the relevant code.
Project index controller:
def index
#projects = current_user.projects.paginate(:page => params[:page], :per_page => 6)
end
Project model:
class Project < ActiveRecord::Base
belongs_to :client
validates :name, presence: true, length: { maximum: 30 }
validates :fee, presence: true, numericality: { only_integer: true,
greater_than_or_equal_to: 0, less_than_or_equal_to: 100000 }
validates :client_id, presence: true
end
Client model:
class Client < ActiveRecord::Base
belongs_to :user
has_many :projects, dependent: :destroy
validates :user_id, presence: true
validates :name, presence: true, length: { maximum: 30 }
validate :user_id_is_valid
private
def user_id_is_valid
errors.add(:user_id, "is invalid") unless User.exists?(self.user_id)
end
end
Relevant part of the User model:
class User < ActiveRecord::Base
has_many :clients, dependent: :destroy
has_many :projects, through: :clients
index.html.erb:
<div id="projects-list">
<% if current_user.projects.any? %>
<h3>Projects</h3>
<ul class="project-list">
<% render #projects %>
</ul>
<%= will_paginate #projects %>
<% end %>
</div>
_project.html.erb:
<li>
<%= link_to "#{project.name}", '#' %>
</li>
It should be:
<%= render #projects %>
Not:
<% render #projects %>
I have the following problem, In UserController#show there has to be a list of posts, but it throws an error as shown in the screen shot:
The part of the code which is responsible to show user posts (show.html.erb)
<div class="span8">
<% if #user.posts.any? %>
<h3>Работы (<%= #user.posts.count %>)</h3>
<ol class="posts">
<%= render #posts %>
</ol>
<%= will_paginate #posts %>
<% end %>
</div>
posts.rb:
class Posts < ActiveRecord::Base
belongs_to :user
default_scope -> { order('created_at DESC') }
validates :description, presence: true, lenght: { minimum: 6 }
validates :user_id, presence: true
end
part of a code in user.rb
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
Your help, thanks in advance is very important.
Excuse for possible mistakes in the text
You should name your model in singular form:
class Post < ActiveRecord::Base
I have a new problem, I Create a web where I upload many images, using nested attributes and polymorphic table, in my index.html I want to show only one image, but I can't find how. But I'm new in rails.
photography.rb
class Photography < ActiveRecord::Base
validates :title, :description, presence: true
belongs_to :user
has_many :images, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :images, :reject_if => lambda { |a| a[:img_str].blank? }, :allow_destroy => true
end
image.rb
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
mount_uploader :img_str, AssetUploader
end
index.html.erb
<% for photo in #photo %>
<%= link_to photo.title, photography_path(photo) %>
<% photo.images.each do |images| %>
<%= images.img_str %>
<% end %>
<% end %>
With the for method I show all the image, try add .first, but says undefined method first for 5:Fixnum. I think that I have to create a helper method, but I not sure. Can anyone help me?. Thanks
Try:
<% for photo in #photo %>
<%= link_to photo.title, photography_path(photo) %>
<%= photo.images.first.img_str if photo.images.any? %>
<% end %>
Also, for is very rarely used in ruby, instead do:
<% #photos.each do |photo| %>
I'm trying to solve a pretty common (as I thought) task.
There're three models:
class Product < ActiveRecord::Base
validates :name, presence: true
has_many :categorizations
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
validates :description, presence: true # note the additional field here
end
class Category < ActiveRecord::Base
validates :name, presence: true
end
My problems begin when it comes to Product new/edit form.
When creating a product I need to check categories (via checkboxes) which it belongs to. I know it can be done by creating checkboxes with name like 'product[category_ids][]'. But I also need to enter a description for each of checked relations which will be stored in the join model (Categorization).
I saw those beautiful Railscasts on complex forms, habtm checkboxes, etc. I've been searching StackOverflow hardly. But I haven't succeeded.
I found one post which describes almost exactly the same problem as mine. And the last answer makes some sense to me (looks like it is the right way to go). But it's not actually working well (i.e. if validation fails). I want categories to be displayed always in the same order (in new/edit forms; before/after validation) and checkboxes to stay where they were if validation fails, etc.
Any thougts appreciated.
I'm new to Rails (switching from CakePHP) so please be patient and write as detailed as possible. Please point me in the right way!
Thank you. : )
Looks like I figured it out! Here's what I got:
My models:
class Product < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations, allow_destroy: true
validates :name, presence: true
def initialized_categorizations # this is the key method
[].tap do |o|
Category.all.each do |category|
if c = categorizations.find { |c| c.category_id == category.id }
o << c.tap { |c| c.enable ||= true }
else
o << Categorization.new(category: category)
end
end
end
end
end
class Category < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
has_many :products, through: :categorizations
validates :name, presence: true
end
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
validates :description, presence: true
attr_accessor :enable # nice little thingy here
end
The form:
<%= form_for(#product) do |f| %>
...
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :categorizations, #product.initialized_categorizations do |builder| %>
<% category = builder.object.category %>
<%= builder.hidden_field :category_id %>
<div class="field">
<%= builder.label :enable, category.name %>
<%= builder.check_box :enable %>
</div>
<div class="field">
<%= builder.label :description %><br />
<%= builder.text_field :description %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the controller:
class ProductsController < ApplicationController
# use `before_action` instead of `before_filter` if you are using rails 5+ and above, because `before_filter` has been deprecated/removed in those versions of rails.
before_filter :process_categorizations_attrs, only: [:create, :update]
def process_categorizations_attrs
params[:product][:categorizations_attributes].values.each do |cat_attr|
cat_attr[:_destroy] = true if cat_attr[:enable] != '1'
end
end
...
# all the rest is a standard scaffolded code
end
From the first glance it works just fine. I hope it won't break somehow.. :)
Thanks all. Special thanks to Sandip Ransing for participating in the discussion. I hope it will be useful for somebody like me.
use accepts_nested_attributes_for to insert into intermediate table i.e. categorizations
view form will look like -
# make sure to build product categorizations at controller level if not already
class ProductsController < ApplicationController
before_filter :build_product, :only => [:new]
before_filter :load_product, :only => [:edit]
before_filter :build_or_load_categorization, :only => [:new, :edit]
def create
#product.attributes = params[:product]
if #product.save
flash[:success] = I18n.t('product.create.success')
redirect_to :action => :index
else
render_with_categorization(:new)
end
end
def update
#product.attributes = params[:product]
if #product.save
flash[:success] = I18n.t('product.update.success')
redirect_to :action => :index
else
render_with_categorization(:edit)
end
end
private
def build_product
#product = Product.new
end
def load_product
#product = Product.find_by_id(params[:id])
#product || invalid_url
end
def build_or_load_categorization
Category.where('id not in (?)', #product.categories).each do |c|
#product.categorizations.new(:category => c)
end
end
def render_with_categorization(template)
build_or_load_categorization
render :action => template
end
end
Inside view
= form_for #product do |f|
= f.fields_for :categorizations do |c|
%label= c.object.category.name
= c.check_box :category_id, {}, c.object.category_id, nil
%label Description
= c.text_field :description
I just did the following. It worked for me..
<%= f.label :category, "Category" %>
<%= f.select :category_ids, Category.order('name ASC').all.collect {|c| [c.name, c.id]}, {} %>