Rails-react - Cannot read property 'count' of undefined(…)

Hej, staram się przenieść GRID-a do ReactJs, niestety przy wywołaniu count na relacji dostaję błąd:

Uncaught TypeError: Cannot read property 'count' of undefined(…)

Skrypt mam podzielony na dwa pliki:

app/asset/javascript/components/datagrid.js.coffee

@DataGrid = React.createClass
        getInitialState: ->
		categories: @props.data
		title: @props.title
	getDefaultProps: ->
		categories: []
	render: ->
		React.DOM.div
			className: 'panel panel-info'
			React.DOM.div
				className: 'panel-heading'
				@state.title
			React.DOM.table
				className: 'table'
				React.DOM.thead null,
					React.DOM.tr null,
						React.DOM.th null, 'ID'
						React.DOM.th null, 'Name'
						React.DOM.th null, 'Articles'
						React.DOM.th null, 'Active'						
				React.DOM.tbody null,
					for category in @state.categories
						React.createElement Category, key: category.id, category: category

app/asset/javascript/components/category.js.coffee

@Category = React.createClass
	render: ->
		React.DOM.tr null,
			React.DOM.td null, @props.category.id
			React.DOM.td null, @props.category.name
			React.DOM.td null,
				React.DOM.span
					className: 'badge'
					@props.category.articles.count
			React.DOM.td null, @props.category.active

Mój stary widok (który w pełni działał):

= link_to 'Create', new_admin_category_path, { :class => 'btn btn-primary', :style => 'margin-bottom: 30px'}
%table{ :class => 'table' }
	%thead
		%th ID
		%th Name
		%th Articles
		%th
	%tbody
		- @categories.each do |category|
			%tr
				%td
					= category.id
				%td
					= link_to category.name, admin_category_articles_path(category)
				%td
					%span{ :class => 'badge' }
						= category.articles.count						
				%td
					= link_to raw('<span class="glyphicon glyphicon-pencil"></span> Edit'), edit_admin_category_path(category), { :class => 'btn btn-primary' }

					= link_to raw('<span class="glyphicon glyphicon-trash"></span> Delete'), admin_category_path(category), method: :delete, :class => 'btn btn-danger', data: { confirm: 'Are you sure?' }

Przekazujesz Reactowi @categories, w ktróym masz kolekcje Categories bez articles. W starym widoku wykonuje się zapytanie dla każdego category.articles.count. W nowym musisz przekazać te articles na początku.

W controllerze spróbuj:
@categories = Category.includes(:articles).as_json(include: :articles)

A w category.js.coffee:
@props.category.articles.length

1 Like