logo
down
shadow

How can display json data two models in Rails index page?


How can display json data two models in Rails index page?

By : user2185804
Date : November 22 2020, 04:01 AM
This might help you You have defined ItemsController to provide both images & items which is not proper, so it will be more relevant if you do it using association but will need changes at view side.
It will be real good format if you pass your data in following format,
code :
def index

  data = { images: Image.all.as_json, items: Item.all.as_json }
  render json: { status: 'SUCCESS', message: 'Loaded images & items', data: data, status: :ok }

end
data = { image: @image.attributes, item: @item.attributes }


Share : facebook icon twitter icon
Rails How to display the data in a index page based on id

Rails How to display the data in a index page based on id


By : Dongwon.jung
Date : March 29 2020, 07:55 AM
it fixes the issue I'd suggest you add satisfaction and rating instance methods in your Bookmodel:
code :
# app/models/book.rb
class Book < ActiveRecord::Base
  ...
  def satisfaction
    book_rating.collect(&:satisfaction).sum.to_f/rating
  end

  def rating
    book_rating.count
  end
end
# app/views/books/index.html.erb
<% @books.each do |book| %>
  <tr>
    ...
    <td><%= book.satisfaction %></td>
    <td><%= book.rating %></td>
    ...
  </tr>
<% end %>
# app/controllers/books_controller.rb
def show
    @book = Book.find(params[:id])
end
# app/models/book.rb
def overall_rating
  ratings.sum('satisfaction + rating + view')/3
end
<% @books.each do |book| %>
  <tr>
    ...
    <td><%= book.overall_rating %></td>
    ...
  </tr>
<% end %>
Rendering json from two models in Rails index

Rendering json from two models in Rails index


By : Kenn Kelly
Date : March 29 2020, 07:55 AM
Does that help I would like to render json in an index method that joins data from a foreign-key related table in Rails. I have a model that has user_id as a foreign key. , You can define custom method and do it. Something like this
code :
class Batch < ActiveRecord::Base
  belongs_to :user

  def user_name
    user.name
  end

end
def index
    panels = Batch.where("user_id = ? or (user_id <> ? and public_panel = true)", current_user.id, current_user.id)
    data = panels.as_json(methods: :user_name, 
                only: [:id, :description, :public_panel, :updated_at, :user_id, :user_name],
                root: false) 
    render json: data
end
Fetch all data from json and display it on the index page

Fetch all data from json and display it on the index page


By : Jap P.
Date : March 29 2020, 07:55 AM
To fix the issue you can do You are setting the same UI elements (img and ul) twice inside a loop. When the loop runs first time, the values are set from the first array element. When the loop runs second time, the SAME elements are overwritten with the new values.
To properly display all elemts from the JSON array, you need two sets of UI elements in the index.html page e.g. two imgs, two uls etc.
In Rails display data from models with through relationships

In Rails display data from models with through relationships


By : user1579314
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Add a new association for users in model TrainingResource, so that you can directly fetch all the users for a training_resource record.
code :
class TrainingResource
  has_many :user_training_resources, dependent: :destroy
  has_many :users, through: :user_training_resources
end
def show
  respond_with @training_resource
end
<% @training_resource.users.each do |user| %>
  <tr>
    <td><%= user.full_name %></td>

    <!-- If you want to display all the training_resources of the user and their statuses -->
    <td><%= user.training_resources.map(&:name).join(', ') %></td>
    <td><%= user.user_training_resources.map(&:status).join(', ')</td>

    <td class="table-actions">
      <!-- Assuming your path is something like '/admin/training_resources/:id/users/:user_id' -->
      <%= link_to 'Delete', admin_user_training_resource_path(@training_resource, user), method: :delete, data: { confirm: 'Are you sure you want to delete this Training resource?' }, class: 'btn btn-danger btn-sm' %>
    </td>
  </tr>
<% end %>
<%- utr = user.user_training_resources.where(training_resource: @training_resource).first %>
<td><%= utr.status %></td>
Display data at index between two models or more in rails

Display data at index between two models or more in rails


By : Tiberium
Date : March 29 2020, 07:55 AM
should help you out Currently, I have two tables countries and users , Add following associations in you models,
user.rb
code :
class User < ActiveRecord::Base
  belongs_to :born_country, foreign_key: :born_country_id, class_name: 'Country'
  belongs_to :live_at_country, foreign_key: :live_at_country_id, class_name: 'Country'

  delegate :name, to: :born_country, prefix: true
  delegate :name, to: :lived_at_country, prefix: true 
end
class Country < ActiveRecord::Base
  has_many :born_users, foreign_key: :born_country_id, class_name: 'User' 
  has_many :live_at_users, foreign_key: :live_at_country_id, class_name: 'User'
end
@users = User.includes(:born_country, :lived_at_country).each do |user|
  puts user.born_at_country_name
  puts user.lived_at_country_name
end
Related Posts Related Posts :
  • Replacing links in the content with processed links in rails using nokogiri
  • Can I force the execution of an active record query chain?
  • ActionController::RoutingError (No route matches [PUT] ) for ajax call
  • How to find all enum fields in a class in Rails
  • Rails 5 - form_with - fields_for assign nested attributes upon creation of parent items.
  • How can we change URL from which webpacker packs are served in Rails 5.1?
  • JSON field into CSV
  • If I shorten the length of each key name in a hash, will that shorten the read/write time of that hash?
  • How to find only Grandparent records where all grandchildren match some criteria in Rails?
  • cant git push heroku master after i tried to change one heroku domain to another heroku domain | ruby on rails app
  • Querying for values from several models
  • How to connect into Action Cable websocket from Arduino?
  • Cleanest way to query polymorphic association?
  • RAILS_ENV, NODE_ENV independent Docker image
  • SQS + Shoryuken: Large Receive Count in FIFO despite auto_delete=true
  • Summernote on Rails Production broken
  • "path_for" ActiveStorage attachments on S3
  • Undefined method `assistants' for ActiveRecord_Relation - Ruby on rails
  • last element of the hash
  • PayPal Express return configuration produces couldn't find Order without an ID
  • Rails Sidekiq - not connecting to Redis
  • Create associated model at the same time as Devise model
  • No route matches [GET] "/oauth/applications"
  • rails default scope with two values
  • uninitialized constant - RoR
  • ForbiddenAttributesError in ruby on rails when update_attributes use
  • Active Storage - Adding File Description / Text - Ruby on Rails 5.2
  • How to use Rails (outside docker) with Postgres (inside docker)?
  • Datagrid Rails : Hide header
  • Reverse a String in Ruby by Reading Backwards
  • How to pass id to an action in the controller - Ruby on Rails
  • Michael Hartl's Rails tutorial chapter 12 — undefined method `users'
  • Ruby on Rails - Linking a user and product controller together, is not working
  • Route constraints: raising exception when there's no match
  • Pass variable from content to layout in Nanoc using Slim
  • How to debug AWS S3 "Access Denied"
  • NoMethodError (undefined method `destroy' for nil:NilClass): even though it is defined
  • Rails template error implicit conversion string to string Heroku
  • Include resize in image_tag with id
  • Redirect to new view with submit_tag in Rails
  • Rails app in EC2 is not reachable but Python is
  • trying to display JSON with 422 error Rails React
  • Nested forms and automatic creation of parent, children
  • Support for multiple domains/subdomains in Rails
  • Model inheritance, the Factory pattern, and self-parsing in Ruby-on-Rails
  • has_many at two levels
  • regular expression to remove substrings delimited by matching double braces
  • What are your crowdsource translation management system recommendations?
  • Show selected name instead of ID in rails index view
  • Rails global content_for
  • rails complex form and ordering with build
  • Given a date, how can I efficiently calculate the next date in a given sequence (weekly, monthly, annually)?
  • What parts of a Ruby-on-Rails application (with reasonably expressive unit tests) should have RDoc?
  • Where to put methods that do simple date formatting
  • What are common ways of implementing web API request throttling/rate-limiting?
  • Linking new users signed in via Facebook connect to existing accounts
  • Rails check if IRB console or webpage
  • As of 2010, what good Rails-based content management systems are there (Typo?)?
  • How to test custom helper in Rails?
  • How can i include image into CSV
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org