Как я могу различить в редукторных редукторах разные переменные экземпляра, поступающие от одного действия в rails backend-api controller - PullRequest
0 голосов
/ 12 мая 2018

Хорошо, у меня есть действие внутри моего контроллера возможных_матчей, называемое setup_possible_matches, которое отображает json.

def setup_possible_matches
   @contemplated_piece = @visible_gor_clothing || GorClothing.where(gender: :male).order(created_at: :desc).first
   @standalone_bottoms = GorClothing.where('standalone = ?', true).where('merch_type = ?', 'bottom').where.not('id = ?', @contemplated_piece).where(gender: :male).order(created_at: :desc)
   @standalone_tops = GorClothing.where('standalone = ?', true).where('merch_type = ?', 'top').where.not('id = ?', @contemplated_piece).where(gender: :male).order(created_at: :desc)
   @suggested_tops = GorClothing.joins(:toggled_pieces).where('merch_type = ?', 'top').where('possible_matches.contemplated_piece_id = ?', @contemplated_piece.id).where(gender: :male).order(created_at: :desc)
   @suggested_bottoms = GorClothing.joins(:toggled_pieces).where('merch_type = ?', 'bottom').where('possible_matches.contemplated_piece_id = ?', @contemplated_piece.id).where(gender: :male).order(created_at: :desc)
   @extra_tops = GorClothing.joins(:toggled_pieces).where('merch_type = ?', 'top').where.not('possible_matches.contemplated_piece_id = ?', @contemplated_piece.id).where('standalone = ?', false).where(gender: :male).order(created_at: :desc)
   @extra_bottoms = GorClothing.joins(:toggled_pieces).where('merch_type = ?', 'bottom').where.not('possible_matches.contemplated_piece_id = ?', @contemplated_piece.id).where('standalone = ?', false).where(gender: :male).order(created_at: :desc)
   render json: {contemplated_piece: @contemplated_piece, standalone_tops: @standalone_tops, standalone_bottoms: @standalone_bottoms, suggested_tops: @suggested_tops, suggested_bottoms: @suggested_bottoms, extra_tops: @extra_tops, extra_bottoms: @extra_bottoms}
end

Внутри db / seed.rb я добавил в базу данных GorClothing:

GorClothing.create(merch_type: 'top', description: 'Perfect for a night out with the boys', gender: 'male', sizes: 'M', colors_available: 'Gray', price: '$59.99', standalone: true, quantity: 5, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/CoolNightClubShirt.png'))}])

GorClothing.create(merch_type: 'top', description: 'Bon Vivant', gender: 'male', sizes: 'M', colors_available: 'black', price: '$64.99', standalone: true, quantity: 6, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/CoolPartyHostShirt.png'))}])

GorClothing.create(merch_type: 'top', description: 'At the beach bar ordering martinis; Learning how to salsa dance; This piece simply communicates that we are unbothered with the things that might weigh down others', gender: 'male', sizes: 'M', colors_available: 'black', price: '$64.99', standalone: true, quantity: 6, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/CoolWhiteShirt.png'))}])

GorClothing.create(merch_type: 'top', description: 'To a baseball game, to a concert, to a get-together, this has casual written all over it.', gender: 'male', sizes: 'M', colors_available: 'black', price: '$64.99', standalone: true, quantity: 6, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/DopeCasualShirt.png'))}])

GorClothing.create(merch_type: 'top', description: 'Honored guest much?', gender: 'male', sizes: 'M', colors_available: 'Gray', price: '$49.99', standalone: true, quantity: 4, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/CoolWineTastingShirt.png'))}])

GorClothing.create(merch_type: 'top', description: 'Too Fresh. Like Fresh Prince of Bel-Air Fresh. Okay, lemme stop.', gender: 'male', sizes: 'M', colors_available: 'White', price: '$39.99', standalone: true, quantity: 4, images_attributes: [{type_of_image: 1, picture: File.open(File.join(Rails.root, 'app/assets/images/FunkyTropicalShirt.png'))}])

Внутри файла views / возможным_матчам / setup_possible_matches.json.builder, у меня есть:

json.contemplated_piece @contemplated_piece :standalone, :merch_type, :gender, :price, :created_at
json.standalone_bottoms @standalone_bottoms :merch_type, :gender, :price, :created_at
json.standalone_tops @standalone_tops :standalone, :merch_type, :gender, :price, :created_at
hash = {:toggled_pieces => {:contemplated_piece_id => @contemplated_piece.id}}
json.suggested_tops @suggested_tops :merch_type, :gender, :created_at, :price json.merge hash
hash - {:toggled_pieces => {:contemplated_piece_id => @contemplated_piece.id}}
json.suggested_bottoms @suggested_bottoms :merch_type, :price, :gender, :created_at, json.merge hash
json.extra_tops @extra_tops :merch_type, :standalone, :gender, :price, :created_at                  
json.extra_bottoms @extra_bottoms :merch_type, :standalone, :price, :gender, :created_at

Действие вызывается редуксным действием внутри файла actions / index.js.

export function defaultPieces(){
    return function(dispatch){
        fetch(`${API_URL}/possible_matches/setup_possible_matches`, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }).then((res) => res.json())
        .then((json) => {
            dispatch(getInitialPieces(json))        
        })
    }
}
export function getInitialPieces(request){
    return {
        type: INITIAL_PIECES,
        payload: request
    }
}

Я пытаюсь получить метод mapStateToProps, чтобы понять разницу между различными переменными экземпляра, которые определены в каком-либо конкретном действии внутри контроллера возможнымMatches от API-интерфейса рельсов, а именно setup_possible_matches выше.

function mapStateToProps(state){
    return {
        UpperComponents: state.possibleMatches.UpperComponents,
        LowerComponents: state.possibleMatches.LowerComponents,
        contemplatedPiece: state.possibleMatches.contemplated_piece,
        extraTops: state.possibleMatches.extraTops,
        extraBottoms: state.possibleMatches.extraBottoms,
        standaloneTops: state.possibleMatches.standaloneTops,
        standaloneBottoms: state.possibleMatches.standaloneBottoms,
        suggestedTops: state.possibleMatches.suggestedTops,
        suggestedBottoms: state.possibleMatches.suggestedBottoms
    };
}

Внутри redurs / index.js у нас есть:

const allReducers = combineReducers({
       possibleMatches: PossibleMatchesReducer,
       routing: routerReducer,
       form: formReducer
});

В консоли я получаю сообщение об ошибке:

Uncaught (в обещании) TypeError: Не удается прочитатьсвойство 'contemplated_piece' неопределенного

Относится к строке внутри редуктора возможного соответствия:

case INITIAL_PIECES:
    console.log('Initial_Pieces: ', action.payload);
    return Object.assign({}, state, {contemplated_piece: action.payload.data.contemplated_piece}, <-- this line
                                    {extraTops: action.payload.data.extra_tops},
                                    {extraBottoms: action.payload.data.extra_bottoms},
                                    {standaloneTops: action.payload.data.standalone_tops},
                                    {standaloneBottoms: action.payload.data.standalone_bottoms},
                                    {suggestedTops: action.payload.data.suggested_tops},
                                    {suggestedBottoms: action.payload.data.suggested_bottoms})

Внутри консоли это то, что возвращается относительно console.log (действие.payload) строка выше:

enter image description here

В консоли мы также получаем TypeError: Невозможно прочитать свойство 'then' из неопределенного

Внутри контроллера возможного соответствия у нас есть:

class PossibleMatches extends Component{
constructor(props){
    super(props);
    this.props.defaultPieces().then(function(results){console.log('Results: ', results)});
}

...rest of Component

function mapDispatchToProps(dispatch) {
 return {
    defaultPieces: () => {
      dispatch(defaultPieces())
    }
  }
}
}

export default connect(mapStateToProps, mapDispatchToProps)(PossibleMatches)

Любая помощь будет оценена.Спасибо.

1 Ответ

0 голосов
/ 13 мая 2018

Итак, получается, что у меня был глупый фильтр before_action внутри контроллера rails, которому был предложен другой вызываемый метод first, который рендерил json, но с двумя массивами внутри хэша. Вот почему я получал результаты, которые я получал в консоли (то, что я разместил выше). Мне просто нужно было убрать это из картинки, и верные данные были возвращены.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...